python - 从“.txt”文件中计算最常用的短语
问题描述
我一直在尝试在 Python 中使用 nltk 从文本文件中查找最常用的短语。这是我的代码:
import nltk
from nltk.collocations import*
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
finder = BigramCollocationFinder.from_words('comments.txt')
finder.apply_freq_filter(2)
finder.nbest(bigram_measures.pmi, 20)
当我输入此代码时,我什么也得不到。我尝试了另一个.txt
文件,但它仍然无法正常工作。难道我做错了什么?
解决方案
该方法BigramCollocationFinder.from_words
需要一个单词列表。你给它一个字符串。但是因为字符串在 Python 中是可迭代的,所以这不会引发异常,但 BigramCollocationFinder 会愉快地分析字符 'c'、'o'、'm'、'm'、'e' ......等等。
因此,为了访问文本文件的内容,我们必须打开它、阅读它、替换非字符字母(包括下划线)并拆分结果文本:
import re
import nltk
from nltk.collocations import BigramCollocationFinder
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
if __name__ == '__main__':
text = open('sampletext.txt').read()
text = re.sub(r'\W', ' ', text)
words = text.split()
finder = BigramCollocationFinder.from_words(words)
finder.apply_freq_filter(2)
r = finder.nbest(bigram_measures.pmi, 30)
print(r)
对于我的示例文件,这导致
[('Juli', 'Monarchie'), ('Makronen', 'Himbeeren'), ('Marschall', 'einst'),
('Praktische', 'Ideale'), ('Sachsens', 'Marschall'), ('Venus', 'Anadyomene'),
('abwesenden', 'Mitglieder'), ('de', 'Dunner'), ('mesdames', 'et'),
('mode', 'Kavalier'), ('säuerliche', 'Geruch'),
('Gottes', 'willen'), ('Lenoir', 'Sergeant'),
('Spitzen', 'Jabot'), ('beleibte', 'Gattin'), ...]
因为我碰巧在这个文本文件中有 The Buddenbrooks 的第一章......
另请注意,您必须打印结果才能看到任何内容。
推荐阅读
- javascript - JavaScript 倒计时时钟将 4:04 显示为 5:14,其余时间似乎都在工作
- javascript - 在交叉路口播放/暂停带声音的视频 - Chrome - DOMException:play() 失败,因为用户没有先与文档交互
- python - 如何根据相机(Python)调整 OpenCV 实时视频源的纵横比
- python - 为什么 tempfile 和 os.chdir() 会抛出 RecursionError?
- python-3.x - 检查 Python 列表元素是否在 Pandas 数据框行中
- xml - 传递值并返回 xslt 中的值
- javascript - 在组件重新渲染或页面在反应中刷新后加载相同的配置
- datastax-java-driver - 如何以编程方式在 CqlSessionBuilder 中设置 DcInferringLoadBalancingPolicy
- sql - 在 Codeigniter 中从数据库中的 3 个表中选择数据
- python - 如何迭代字符串的DataFrame并在结果上应用条件