用于计算nltk中频繁字对的Python代码

时间:2014-01-22 13:29:27

标签: python regex nltk

我很困惑如何在文件中找到频繁的单词对。我首先获得了bigrams但是如何从这里开始?我在尝试使用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)

2 个答案:

答案 0 :(得分:1)

您似乎在没有导入的情况下致电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', ','))]

答案 1 :(得分:0)

听起来你只想要单词对列表。如果是这样,我认为您的意思是使用finder.score_ngrams,如下所示:

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

可以使用其他评分指标。听起来你只想要频率,但是一般Ngrams的其他评分指标就在这里 - http://nltk.googlecode.com/svn-/trunk/doc/api/nltk.metrics.association.NgramAssocMeasures-class.html