Here's a Python script that exports your Outlook emails to a CSV file and prepares them for fine-tuning an LLM:
import win32com.client
import csv
import re
def clean_text(text):
# Remove extra whitespace and newline characters
text = re.sub(r'\s+', ' ', text).strip()
# Remove URLs
text = re.sub(r'http\S+', '', text)
# Remove email addresses
text = re.sub(r'\S+@\S+', '', text)
return text
def export_emails_to_csv(file_path):
outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")
inbox = outlook.GetDefaultFolder(6)
messages = inbox.Items
with open(file_path, 'w', newline='', encoding='utf-8') as file:
writer = csv.writer(file)
writer.writerow(['Subject', 'Body'])
for message in messages:
subject = clean_text(message.Subject)
body = clean_text(message.Body)
writer.writerow([subject, body])
print(f"Emails exported to {file_path}")
# Specify the file path where you want to save the CSV file
csv_file_path = 'outlook_emails.csv'
# Export emails to CSV
export_emails_to_csv(csv_file_path)
This script does the following:
-
We import the necessary libraries: win32com.client for interacting with Outlook, csv for writing to a CSV file, and re for text cleaning using regular expressions.
-
We define a clean_text() function that takes a text string as input and performs some basic text cleaning operations:
- Removes extra whitespace and newline characters using
re.sub().
- Removes URLs using a regular expression pattern.
- Removes email addresses using a regular expression pattern.
-
We define an export_emails_to_csv() function that takes the file path where the CSV file will be saved as input:
- It creates an instance of the Outlook application and retrieves the default inbox folder.
- It opens the specified CSV file in write mode with UTF-8 encoding.
- It writes the header row to the CSV file with the columns 'Subject' and 'Body'.
- It iterates over each message in the inbox folder.
- For each message, it cleans the subject and body using the
clean_text() function.
- It writes the cleaned subject and body to a new row in the CSV file.
-
We specify the file path where you want to save the CSV file.
-
We call the export_emails_to_csv() function with the specified file path to export the emails to the CSV file.
After running this script, your Outlook emails will be exported to the specified CSV file, with the subject and body text cleaned and ready for fine-tuning an LLM.
Note: Make sure you have the pywin32 library installed (pip install pywin32) to use the win32com.client module for interacting with Outlook.