Chapter 9 Exercise 2 Python for Everybody problem with dictionary and loops

Viewed 49

I'm not sure why I keep the wrong answer. I first found the days through for line in hand loop and then added key and value through dictionary, yet I don't get the output that I thought about. Could you please help me? than you!

Exercise 2: Write a program that categorizes each mail message by which day of the week the commit was done. To do this look for lines that start with “From”, then look for the third word and keep a running count of each of the days of the week. At the end of the program print out the contents of your dictionary (order does not matter).

Sample Line:

From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008

Sample Execution:

python dow.py

Enter a file name: mbox-short.txt
{'Fri': 20, 'Thu': 6, 'Sat': 1}

Here is my code

#mbox-short.txt
fname = input("Enter a file name: ")
hand = open(fname)

counts = dict()
for line in hand:
    line = line.rstrip()
    if not line.startswith('From '): continue
    words = line.split()
    words = words[2]
    for word in words:
        if word not in counts:
            counts[word] = 1
        else:
            counts[word] += 1

print(counts)

output

{'S': 1, 'a': 1, 't': 1, 'F': 20, 'r': 20, 'i': 20, 'T': 6, 'h': 6, 'u': 6}
1 Answers

There are some logic errors in your code, you could try this and compare with yours. (2nd split is wrongly placed!)

If you have any questions, please ask later afterwards. (it's done long time ago, assuming the data file is still available)

dc_days = {}                      # Initializes the dictionary
file_name = input('Enter a file name: ')

try:
    fp = open(file_name)
except FileNotFoundError:
    print('File cannot be opened:', file_name)
    exit()

for line in fp:
    words = line.split()
    
    if len(words) < 3 or words[0] != 'From':
        continue
    else:
        if words[2] not in dc_days:
            dc_days[words[2]] = 1       # seen first time
        else:
            dc_days[words[2]] += 1      # more to count

print(dc_days)
    
Related