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 Sat Jan 5 09:14:16 2008

Sample Execution:

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: ')
    fhand = open(fname)
except FileNotFoundError:
    print('File cannot be opened:', fname)

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


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: , I am doing this on a Jupyter Notebook

1 answer

  • answered 2021-02-23 03:16 anmsan

    Using this file:

    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')

    If it works your output should be:

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