Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
131 views
in Technique[技术] by (71.8m points)

python - find the occurrence of the word in a file

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 .

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...