Chapter 9 Exercise 2 Python for Everybody

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:

d = dict()                      
fname = input('Enter a file name: ')
try:
    fhand = open(fname)
except FileNotFoundError:
    print('File cannot be opened:', fname)
    exit()

for line in fhand:
    words = line.split()
    if len(words) < 3 or words[0] != 'From':
        continue
    else:
        if words[2] not in dictionary_days:
            d[words[2]] = 1       
        else:
            d[words[2]] += 1      

print(d) 

This is the output I get Enter a file name:

Then I enter mbox-short.txt and receive this output File cannot be opened: mbox-short.txt

I don't really know where to start. Here is the mbox-short.txt file: https://www.py4e.com/code3/mbox-short.txt , I am doing this on a Jupyter Notebook

1 answer

  • answered 2021-02-23 03:16 anmsan

    Using this file: http://www.py4inf.com/code/mbox-short.txt

    1. Download to your computer then upload into Jupyter OR create a new text file and copy and paste it
    2. Save it as mbox-short.txt
    3. Test whether it works using:
    fhand = open('mbox-short.txt')
    print(fhand)
    

    If it works your output should be:

    <_io.TextIOWrapper name='mbox-short.txt' mode='r' encoding='cp1252'>