我有一个标签为“all.txt”的文本文件,它包含一个普通的英文段落
出于某种原因,当我运行这段代码时:
import nltk
from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
# change this to read in your data
finder = BigramCollocationFinder.from_words(('all.txt'))
# only bigrams that appear 3+ times
#finder.apply_freq_filter(3)
# return the 10 n-grams with the highest PMI
print finder.nbest(bigram_measures.pmi, 10)
我得到以下结果:
[('.', 't'), ('a', 'l'), ('l', '.'), ('t', 'x'), ('x', 't')]
我做错了什么,因为我只收到信件?我要找的是单词而不是字母!
这是“all.txt”中内容的示例,因此您可以了解正在处理的内容: “反对这项计划的不仅仅是民主党人。全国各地的美国人都表示反对这项计划。我的民主党同事和我有一个更好的计划,将加强道德规则,以提高国会的问责制,并确保立法得到了适当的考虑。共和党的计划未能弥补漏洞,允许在成员阅读之前考虑立法。”
最佳答案
第一个问题是您实际上并没有读入文件,您只是将包含文件路径的字符串传递给函数,第二个问题是您首先需要使用分词器。解决第二个问题:
from nltk.tokenize import word_tokenize
finder = BigramCollocationFinder.from_words(word_tokenize("This is a test sentence"))
print finder.nbest(bigram_measures.pmi, 10)
产生 [('This', 'is'), ('a', 'test'), ('is', 'a'), ('test', 'sentence')]
请注意,您可能想要使用不同的分词器——分词包文档将对各种选项进行更多解释。
在第一种情况下,您可以使用如下内容:
with open('all.txt', 'r') as data_file:
finder = BigramCollocationFinder.from_words(word_tokenize(data_file.read())
关于python - NLTK 双字母查找器的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14640230/