繁体   English   中英

Python代码在nltk中计算频繁单词对

[英]Python code to count frequent word pairs in nltk

我很困惑如何在文件中查找频繁的单词对。我首先获得了二元组,但如何从这里开始呢? 我尝试在应用nltk.bigrams之前使用regexp剥离标点符号

raw=open("proj.txt","r").read()
tokens=nltk.word_tokenize(raw)
pairs=nltk.bigrams(tokens)
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()
finder = BigramCollocationFinder.from_words(pairs)
finder.apply_freq_filter(3)
finder.nbest(bigram_measures.pmi, 10)

您似乎在不导入的情况下调用了BigramCollocationFinder 正确的路径是nltk.collocations.BigramCollocationFinder 因此,您可以尝试执行此操作(确保您的文本文件包含文本!):

>>> import nltk
>>> raw = open('test2.txt').read()
>>> tokens = nltk.word_tokenize(raw)
# or, to exclude punctuation, use something like the following instead of the above line:
# >>> tokens = nltk.tokenize.RegexpTokenizer(r'\w+').tokenize(raw)
>>> pairs = nltk.bigrams(tokens)
>>> bigram_measures = nltk.collocations.BigramAssocMeasures()
>>> trigram_measures = nltk.collocations.TrigramAssocMeasures()
>>> finder = nltk.collocations.BigramCollocationFinder.from_words(pairs)  # note the difference here!
>>> finder.apply_freq_filter(3)
>>> finder.nbest(bigram_measures.pmi, 10)  # from the Old English text of Beowulf
[(('m\xe6g', 'Higelaces'), ('Higelaces', ',')), (('bearn', 'Ecg\xfeeowes'), ('Ecg\xfeeowes', ':')), (("''", 'Beowulf'), ('Beowulf', 'ma\xfeelode')), (('helm', 'Scyldinga'), ('Scyldinga', ':')), (('ne', 'cu\xfeon'), ('cu\xfeon', ',')), ((',', '\xe6r'), ('\xe6r', 'he')), ((',', 'helm'), ('helm', 'Scyldinga')), ((',', 'bearn'), ('bearn', 'Ecg\xfeeowes')), (('Ne', 'w\xe6s'), ('w\xe6s', '\xfe\xe6t')), (('Beowulf', 'ma\xfeelode'), ('ma\xfeelode', ','))]

听起来您只想要单词对列表。 如果是这样,我想您是说像这样使用finder.score_ngrams

bigram_measures = nltk.collocations.BigramAssocMeasures()
finder = BigramCollocationFinder.from_words(tokens)
scores = finder.score_ngrams( bigram_measures.raw_freq )
print scores

可以使用其他评分指标。 这听起来像你只想要的频率,但对于一般的n-gram其他评价指标的位置- http://nltk.googlecode.com/svn-/trunk/doc/api/nltk.metrics.association.NgramAssocMeasures-class.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM