首页 > 解决方案 > 从“.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)

资料来源:nltk.org

当我输入此代码时,我什么也得不到。我尝试了另一个.txt文件,但它仍然无法正常工作。难道我做错了什么?

标签: pythonnltk

解决方案


该方法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 的第一章......

另请注意,您必须打印结果才能看到任何内容。


推荐阅读