-1

I am trying to open a file, iterate over each line, and do a count of a specific word in each line to add to a Dictionary.

For the sake of this question, the file has values in it that look like this:

From some.email@address.ac.za Sat Jan  5 09:14:16 2008
From some.email@address.ac.za Sat Jan  5 09:14:16 2008
From some.email@address.ac.za Fri Jan  5 09:14:16 2008
From some.email@address.ac.za Wed Jan  5 09:14:16 2008
From some.email@address.ac.za Tue Jan  5 09:14:16 2008
From some.email@address.ac.za Sat Jan  5 09:14:16 2008
From some.email@address.ac.za Sat Jan  5 09:14:16 2008
From some.email@address.ac.za Sat Jan  5 09:14:16 2008

What I want to do is read in the file, iterate over each line, and keep a count of the days of the week and return that in a Dictionary. So the results would look something like this:

{'Sat': 5, 'Fri': 1, 'Wed': 1, 'Tue': 1}

I have it to the point of reading in the file and splitting at the whitespace, and appending to a list. After that I am stuck and can't drill down to that specific section of test in each list.

Any ideas?

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

counts = dict()
l1 = []
for line in fhand:
    line = line.split()
    l1.append(line)
for date in l1:
    for day in date:
        if day[2] not in counts:
            counts[day] = 1
        else:
            counts[day] += 1
r.ook
  • 13,466
  • 2
  • 22
  • 39
JD2775
  • 3,658
  • 7
  • 30
  • 52

1 Answers1

2
from collections import defaultdict
fname = input('Enter the file name: ')
try:
    fhand = open(fname)
except:
    print('File cannot be opened:', fname)
    exit()

counts = defaultdict(int)
l1 = []
for line in fhand:
    line = line.split()
    for word in line:
        if word in ['Sun', 'Mon', 'Tue', 'Wed', 'Thrus', 'Fri', 'Sat']:
            counts[word] += 1
print(counts)  

After reading each line and splitting it into words, you can check if the word is a day name, and if it is, then update the value corresponding to that day.

taurus05
  • 2,491
  • 15
  • 28