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

Python 存储文本文件中出现的每个单词的计数,python,Python,我想将文本文件中出现的每个单词的计数存储在字典中。我是说 fob= open('D:/project/report.txt','r') 我可以将这些行存储到列表中,但我需要将这些行拆分为单个单词,并最终存储它们的计数(就像在附加数据中一样) 我该怎么做?什么是有效的方法呢?对于Python2.7+ from collections import Counter with open('D:/project/report.txt','r') as fob: c = Counter(wor

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

fob= open('D:/project/report.txt','r')
我可以将这些行存储到列表中,但我需要将这些行拆分为单个单词,并最终存储它们的计数(就像在附加数据中一样)


我该怎么做?什么是有效的方法呢?

对于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
对于较老的蟒蛇或讨厌
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
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
对于较老的蟒蛇或讨厌
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