PY4E课程官网:https://www.py4e.com/
参考文章(Github):
Assignment 9.4
Write a program to read through the mbox-short.txt and figure out who has the sent the greatest number of mail messages. The program looks for 'From ' lines and takes the second word of those lines as the person who sent the mail. The program creates a Python dictionary that maps the sender's mail address to a count of the number of times they appear in the file. After the dictionary is produced, the program reads through the dictionary using a maximum loop to find the most prolific committer.
编写一个程序来读取mbox-short.txt,并将其作为一个程序来使用。计算出谁发送的邮件数量最多。该程序寻找'From'行,并取其中的第二个字行作为发送邮件的人。该程序创建了一个Python字典将发件人的邮件地址映射到他们出现在的次数统计中的文件。词典制作完成后。程序使用最大循环来读取字典,找出最多产的提交者。
import sys
fname = input('Enter the file name: ')
try:
fhand = open(fname)
except:
print(fname, 'File does not exist ')
sys.exit()
sender_dict = dict()
for line in fhand:
words = line.split()
if words and words[0] == 'From':
sender_dict[words[1]] = sender_dict.get(words[1], 0)+1
bigcount = None
bigname = None
for name, count in sender_dict.items():
if bigcount is None or count > bigcount:
bigname = name
bigcount = count
print(sender_dict)
print("The most prolific committer is", bigname,"and it has permitted",bigcount,"times.")
>>>Enter the file name: mbox-short.txt
{'stephen.marquard@uct.ac.za': 2, 'louis@media.berkeley.edu': 3, 'zqian@umich.edu': 4, 'rjlowe@iupui.edu': 2, 'cwen@iupui.edu': 5, 'gsilver@umich.edu': 3, 'wagnermr@iupui.edu': 1, 'antranig@caret.cam.ac.uk': 1, 'gopal.ramasammycook@gmail.com': 1, 'david.horwitz@uct.ac.za': 4, 'ray@media.berkeley.edu': 1}
The most prolific committer is cwen@iupui.edu and it has permitted 5 times.