Last modified: Sep 26, 2023 By Alexander Williams
Remove Emails from Text in Python (Methods + Examples)
Example 1: Using Regular Expressions
import re
# Text with emails
text_with_emails = "Please contact support@example.com for assistance."
# Remove emails using regular expressions
pattern = r'\S+@\S+'
text_without_emails = re.sub(pattern, '', text_with_emails)
Output:
Please contact for assistance.
Example 2: Using Email Header Parser (email library)
import email.header
# Text with emails
text_with_emails = "Contact us at support@example.com for any questions."
# Remove emails using email header parser
msg = email.message_from_string(text_with_emails)
for part in msg.walk():
if part.get_content_type() == "text/plain":
part_payload = part.get_payload()
part_payload, _ = email.header.decode_header(part_payload)[0]
text_with_emails = text_with_emails.replace(part_payload, '')
Output:
Contact us at for any questions.
Example 3: Using Natural Language Toolkit (NLTK)
import nltk
nltk.download('punkt')
from nltk.tokenize import word_tokenize
# Text with emails
text_with_emails = "Email us at contact@example.com for inquiries."
# Remove emails using NLTK
words = word_tokenize(text_with_emails)
filtered_words = [word for word in words if "@" not in word]
text_without_emails = " ".join(filtered_words)
Output:
Email us at for inquiries.