DEV Community

Durga Pokharel
Durga Pokharel

Posted on

Day 34 Of 100DaysOfCode : Python Code To Find Count Of Mail

Today is my 34 day of #100DaysOfCode and Python. Today I tried to write some code on python access to web data and data structure on python. Complete some assignment on coursera.

Below is the python code I tried to write to find the count of mail from the file and from whom maximum times mail come.

Python Code

At first we open file. Set counts to zero at first. There is empty list for mails. I write simple loop to find the mail. There is empty dictionary to store mail as a key and number of count as a value.

fhand = open('mbox-short.txt')
count = 0
emails = []
for line in fhand:
    words = line.split()
    # print('Debug:', words)
    if len(words) == 0 : continue
    if words[0] != 'From' : continue
    emails.append(words[1])
#print(emails)
d = {}
for email in emails:
    if email not in d:
        d[email] = 1
    else:
        d[email] += 1
#print(d)
max(d)
nd = {k: v for k, v in list(reversed(sorted(d.items(), key=lambda item: item[1])))}
nd
Enter fullscreen mode Exit fullscreen mode

The output of this code is given below.

{'cwen@iupui.edu': 5,
 'david.horwitz@uct.ac.za': 4,
 'zqian@umich.edu': 4,
 'gsilver@umich.edu': 3,
 'louis@media.berkeley.edu': 3,
 'rjlowe@iupui.edu': 2,
 'stephen.marquard@uct.ac.za': 2,
 'ray@media.berkeley.edu': 1,
 'gopal.ramasammycook@gmail.com': 1,
 'antranig@caret.cam.ac.uk': 1,
 'wagnermr@iupui.edu': 1}
Enter fullscreen mode Exit fullscreen mode

To find by whom we got maximum mail is find by

print(f"This {list(nd.items())[0][0]} send mail most i.e {list(nd.items())[0][1]} times.")
Enter fullscreen mode Exit fullscreen mode

Output is,

This cwen@iupui.edu send mail most i.e 5 times.
Enter fullscreen mode Exit fullscreen mode

Day 34 Of #100DaysOfCode and #Python
* Web access on python
* Data structure on python
* Python program to find the maximum count of mail.#100DaysOfCode ,#CodeNewbie ,#Python ,#beginners pic.twitter.com/pTaNyNoczI

— Durga Pokharel (@mathdurga) January 27, 2021

Top comments (0)