Write a program to read through a mail log, build a histogram using a dictionary to count how many messages have come from each.Enter file name: mbox-short.txt {'gopal.ramasammycook@gmail.com': 1, 'louis@media.berkeley.edu': 3, 'cwen@iupui.edu': 5, 'antranig@caret.cam.ac.uk': 1, 'rjlowe@iupui.edu': 2, 'gsilver@umich.edu': 3, 'david.horwitz@uct.ac.za': 4, 'wagnermr@iupui.edu': 1, 'zqian@umich.edu': 4, 'stephen.marquard@uct.ac.za': 2, 'ray@media.berkeley.edu': 1} Download the mbox-short.txt file from the txtfiles folder.
时间: 2023-12-31 12:04:38 浏览: 262
HW. middleton.rar_HW. middleton_Middleton_Middleton class A_Mid
5星 · 资源好评率100%
Here's a Python program that reads through a mail log, builds a histogram using a dictionary to count how many messages have come from each:
```python
fname = input("Enter file name: ")
try:
fhand = open(fname)
except:
print("File not found:", fname)
exit()
counts = dict()
for line in fhand:
if line.startswith("From "):
words = line.split()
email = words[1]
counts[email] = counts.get(email, 0) + 1
print(counts)
```
This program prompts the user to enter the file name, opens the file, and then reads through each line. If a line starts with "From ", it splits the line into words and extracts the email address (which is always the second word in this format of log). It then uses a dictionary to keep a count of how many messages have come from each email address. Finally, it prints out the histogram as a dictionary.
阅读全文