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

标签 python file count word

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

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

谁能帮帮我?提前致谢。

最佳答案

使用Counter的update方法。示例:

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 - 查找文件中单词的出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15083119/

相关文章:

python - 为什么在聚类之前跨行而非列进行数据标准化(预处理)

python - 向 auth_user 表添加只能具有选择性值的字段

c - 如何打开临时文件并获取其文件名?

python - 如何从文件中读取并将其作为整数放入列表中? Python

php - 从一年的开始日期开始计算假期天数,然后每年计算

sql - PostgreSQL:根据空值或非空值排除已连接的 ID

python - 为大型数据集在 pandas 中排序

python - Django同一个表的多个外键

python - 搜索文本文件并打印行号

Mysql 内部连接管理 count() 行为