python - 查找文件中出现的单词 [英] python - find the occurrence of the word in a file

查看:27
本文介绍了python - 查找文件中出现的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试查找文件中出现的单词数.我有一个文本文件(TEST.txt),文件内容如下:

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

我期望的结果是:

{ 'ashwin':1, 'programmer ':2,'india':2, 'amith ':1}

我使用的代码是:

for line in open(TEST.txt,'r'):
    word = Counter(line.split())
    print word

我得到的结果是:

Counter({'ashwin': 1, 'programmer': 1,'india':1})
Counter({'amith': 1, 'programmer': 1,'india':1})

有人可以帮我吗?提前致谢.

Can any one please help me? Thanks in advance .

推荐答案

使用 Counter 的 update 方法.示例:

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)

输出:

Counter({'india': 2, 'programmer': 2, 'amith': 1, 'ashwin': 1})

这篇关于python - 查找文件中出现的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆