我一直在研究网络上的不同来源并尝试了各种方法,但只能找到如何计算独特单词的频率而不是独特短语的频率。我目前的代码如下:
import collections
import re
wanted = set(['inflation', 'gold', 'bank'])
cnt = collections.Counter()
words = re.findall('\w+', open('02.2003.BenBernanke.txt').read().lower())
for word in words:
if word in wanted:
cnt [word] += 1
print (cnt)
如果可能的话,我还想统计一下“中央银行”和“高通胀”这两个词在本文中出现的次数。感谢您提供的任何建议或指导。
最佳答案
首先,这就是我生成您所做的 cnt
的方式(以减少内存开销)
def findWords(filepath):
with open(filepath) as infile:
for line in infile:
words = re.findall('\w+', line.lower())
yield from words
cnt = collections.Counter(findWords('02.2003.BenBernanke.txt'))
现在,关于短语的问题:
from itertools import tee
phrases = {'central bank', 'high inflation'}
fw1, fw2 = tee(findWords('02.2003.BenBernanke.txt'))
next(fw2)
for w1,w2 in zip(fw1, fw2)):
phrase = ' '.join([w1, w2])
if phrase in phrases:
cnt[phrase] += 1
希望对你有帮助
关于python - 在 Python 3.3.2 中计算短语频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19920572/