python单词查询,python - 在文件中查找单词的出现

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值