Reputation:
i need to write a function create_dictionary(filename) that reads the named file and returns a dictionary mapping from object names to occurrence counts (the number of times the particular object was guessed). For example, given a file mydata.txt containing the following:
abacus
calculator
modern computer
abacus
modern computer
large white thing
modern computer
Here's my program, and it works fine for non-empty text files.
from collections import Counter
def create_dictionary(filename):
"""Cool Program"""
keys = Counter()
s = open(filename,'r').read().strip()
keys = (Counter(s.split('\n')))
dictionary = create_dictionary('mydata.txt')
for key in dictionary:
print(key + ': ' + str(dictionary[key]))
return keys
Out will be as:
{'abacus': 2, 'calculator': 1, 'modern computer': 3, 'large white thing': 1}
When I have an empty file (eg. blank.txt), the function must ignore any and all blank lines. So, the print statement must return a blank. But I am getting ': 1' no matter what I tried. And oh, here are some simple constraints: Here are some constraints:
Any advise?
Upvotes: 0
Views: 809
Reputation: 33335
lines = open(filename,'r').readlines()
keys = Counter([line.strip() for line in lines if line.strip()])
Upvotes: 2