I am trying to find the count of words that occured in a file. I have a text file (TEST.txt
) the content of the file is as follows:
ashwin programmer india
amith programmer india
The result I expect is:
{ 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1}
The code I am using is:
for line in open(TEST.txt,'r'):
word = Counter(line.split())
print word
The result I get is:
Counter({'ashwin': 1, 'programmer': 1,'india':1})
Counter({'amith': 1, 'programmer': 1,'india':1})
Can any one please help me? Thanks in advance .
Use the update
method of Counter. Example:
from collections import Counter
data = '''\
ashwin programmer india
amith programmer india'''
c = Counter()
for line in data.splitlines():
c.update(line.split())
print(c)
Output:
Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})