forked from jmelahman/python-for-everybody-solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexercise9_3.py
37 lines (31 loc) · 1.2 KB
/
exercise9_3.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"""
Exercise 9.3: Write a program to read through a mail log, build a histogram
using a dictionary to count how many messages have come from each email
address, and print the dictionary.
Enter file name: mbox-short.txt
{'[email protected]': 2, '[email protected]': 3,
'[email protected]': 3, '[email protected]': 1,
'[email protected]': 1, '[email protected]': 1,
'[email protected]': 4, '[email protected]': 1}
Python for Everybody: Exploring Data Using Python 3
by Charles R. Severance
Solution by Jamison Lahman, May 31, 2017
"""
dictionary_addresses = dict() #Initializes the dictionary
fname = input('Enter file name: ')
try:
fhand = open(fname)
except:
print('File cannot be opened:', fname)
exit()
for line in fhand:
words = line.split()
if len(words) == 0 or len(words) < 2 or words[0] != 'From':
continue
else:
if words[1] not in dictionary_addresses:
dictionary_addresses[words[1]] = 1 #First entry
else:
dictionary_addresses[words[1]] += 1 #Additional counts
print(dictionary_addresses)