问题描述
我知道如何使用NLTK来获得二元组和三元组的搭配,并将它们应用于我自己的语料库.代码如下.
I know how to get bigram and trigram collocations using NLTK and I apply them to my own corpora. The code is below.
我唯一的问题是如何用PMI值打印出图表?我多次搜索NLTK文档.是我遗漏了一些东西,还是不在那里.
My only problem is how to print out the birgram with the PMI value? I search NLTK documentation multiple times. It's either I'm missing something or it's not there.
import nltk
from nltk.collocations import *
myFile = open("large.txt", 'r').read()
myList = myFile.split()
myCorpus = nltk.Text(myList)
trigram_measures = nltk.collocations.TrigramAssocMeasures()
finder = TrigramCollocationFinder.from_words((myCorpus))
finder.apply_freq_filter(3)
print finder.nbest(trigram_measures.pmi, 500000)
推荐答案
如果您查看nlkt.collocations.TrigramCollocationFinder
的源代码(请参阅 http://www.nltk.org/_modules/nltk/collocations.html ),您会发现它返回了TrigramCollocationFinder().score_ngrams
:
If you take a look at the source code for nlkt.collocations.TrigramCollocationFinder
(see http://www.nltk.org/_modules/nltk/collocations.html), you'll find that it returns a TrigramCollocationFinder().score_ngrams
:
def nbest(self, score_fn, n):
"""Returns the top n ngrams when scored by the given function."""
return [p for p,s in self.score_ngrams(score_fn)[:n]]
因此您可以直接调用score_ngrams()
而无需获取nbest
,因为它仍然会返回排序列表.:
So you could call the score_ngrams()
directly without getting the nbest
since it returns a sorted list anyways.:
def score_ngrams(self, score_fn):
"""Returns a sequence of (ngram, score) pairs ordered from highest to
lowest score, as determined by the scoring function provided.
"""
return sorted(self._score_ngrams(score_fn),
key=_itemgetter(1), reverse=True)
尝试:
import nltk
from nltk.collocations import *
from nltk.tokenize import word_tokenize
text = "this is a foo bar bar black sheep foo bar bar black sheep foo bar bar black sheep shep bar bar black sentence"
trigram_measures = nltk.collocations.TrigramAssocMeasures()
finder = TrigramCollocationFinder.from_words(word_tokenize(text))
for i in finder.score_ngrams(trigram_measures.pmi):
print i
[输出]:
(('this', 'is', 'a'), 9.047123912114026)
(('is', 'a', 'foo'), 7.46216141139287)
(('black', 'sheep', 'shep'), 5.46216141139287)
(('black', 'sheep', 'foo'), 4.877198910671714)
(('a', 'foo', 'bar'), 4.462161411392869)
(('sheep', 'shep', 'bar'), 4.462161411392869)
(('bar', 'black', 'sheep'), 4.047123912114026)
(('bar', 'black', 'sentence'), 4.047123912114026)
(('sheep', 'foo', 'bar'), 3.877198910671714)
(('bar', 'bar', 'black'), 3.047123912114026)
(('foo', 'bar', 'bar'), 3.047123912114026)
(('shep', 'bar', 'bar'), 3.047123912114026)
这篇关于如何获得带有NLTK搭配的三联词的PMI分数? Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!