To write a Python script that identifies the most common email domains present in a CSV file, you will need to follow these steps:
- Read the CSV file: Assume the CSV file has emails in a specific column, let's say column name is "Email".
- Extract the domain from each email: Split the email address at the "@" symbol and take the second part.
- Count the frequency of each domain: Use a dictionary or a
collections.Counter object to keep track of domain frequencies.
- Display the most common domains: Sort the domains by their frequency and display them.
Here's an example script to achieve this:
import csv
from collections import Counter
def extract_domain(email):
"""Extract and return the domain from an email address."""
return email.split('@')[-1]
def count_email_domains(csv_filename):
"""Count email domains from a CSV file and return the most common ones."""
domains = Counter() # A Counter object to hold the domain counts
with open(csv_filename, mode='r', encoding='utf-8') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
email = row.get('Email', '') # Replace 'Email' with the actual column name in your CSV
if email: # If email is not empty
domain = extract_domain(email)
domains[domain] += 1
return domains
def main():
csv_filename = 'emails.csv' # Replace with your actual CSV file path
domain_counts = count_email_domains(csv_filename)
# Display the 5 most common domains
print("Most common email domains:")
for domain, count in domain_counts.most_common(5):
print(f"{domain}: {count}")
if __name__ == "__main__":
main()
Notes:
- CSV Format: This script assumes that the CSV file has headers and that one of the columns is named "Email" containing the email addresses. Please adjust the column name accordingly in the
row.get('Email', '') part if your column is named differently.
- File Path: Replace
'emails.csv' in the main function with the path to your actual CSV file.
- Common Domains: The script displays the 5 most common email domains. You can adjust the number inside
most_common(5) to display more or fewer domains.
This script provides a basic structure. Depending on the structure of your CSV file and specific requirements, you might need to adjust the script accordingly.