python - 存储文本文件中出现的每个单词的计数

标签 python

我想将文本文件中出现的每个单词的计数存储在字典中。我的意思是

fob= open('D:/project/report.txt','r')

我可以将这些行存储到一个列表中,但我需要将这些行拆分成单独的单词,最后存储它们的计数(就像在字典中一样)。

lst=fob.radlines()

#This doesn't work, gives error
#AttributeError: 'list' object has no attribute 'split' 
mylst=lst.split()

我怎样才能做到这一点?做到这一点的有效方法是什么?

最佳答案

对于 Python 2.7+

from collections import Counter

with open('D:/project/report.txt','r') as fob:
    c = Counter(word for line in fob for word in line.split())

对于 Python 2.5+

from collections import defaultdict
dd = defaultdict(int)

with open('D:/project/report.txt','r') as fob:
    for line in fob:
        for word in line.split():
            dd[word] += 1

对于老 python 或讨厌defaultdict的人

d = {}

with open('D:/project/report.txt','r') as fob:
    for line in fob:
        for word in line.split():
            d[word] = d.get(word, 0) + 1

关于python - 存储文本文件中出现的每个单词的计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15737173/

相关文章:

python - 如何创建多个处于不同位置的 turtle ?

python - 使用 GridSearchCV 时跳过禁止的参数组合

python - 一个函数打印 Python 中具有不同参数集的多个函数的返回值

Python:将类型提示与注释一起使用

python - 文件虽然存在但未找到

python - 计算字符串中重叠的子串

python - 每月运行一次python脚本,将参数传递给脚本

python - 读取带有重复标题的 CSV 文件

python - 继承列表 : Creating division by other lists, 整数和 float

python - 是否有更 pythonic 的方式来填充此列表?