在nltk协同词中结合过滤器
我想用 nltk collocations 来对二元组(bigrams)应用多个过滤器。问题是这样的:
我需要保留那些出现超过一次的二元组,或者在一个单词列表中的二元组。注意,我想保留那些在单词列表中的二元组——如果我想把它们去掉,我可以简单地一个一个地应用过滤器。
我知道有一个频率过滤器,而且我也可以用下面的代码单独检查单词是否在列表中:
lambda *w: w not in [w1,w2,w3]
但是我不知道如何在这个函数中检查二元组的频率。
我们如何获取传递给 lambda 的二元组的频率呢?
1 个回答
1
好的,你想要同时根据频率和一个单词列表来过滤内容。那么,你需要创建一个函数,这个函数会根据得分字典和一个定义好的单词列表来构建过滤器,像这样:
def create_filter_minfreq_inwords(scored, words, minfreq):
def bigram_filter(w1, w2):
return (w1 not in words and w2 not in words) and (
(w1, w2) in scored and scored[w1, w2] <= minfreq)
return bigram_filter
接下来,你需要先创建一个字典,用来记录频率。这个过程可以使用 finder.score_ngrams,并结合 BigramAssocMeasures.raw_freq 来实现。然后,使用上面提到的函数来创建二元组过滤器。下面是一个逐步的示例:
import nltk
# create some text and tokenize it
text = "This is a text. Written for test purposes, this is a text."
tokens = nltk.wordpunct_tokenize(text)
# initialize finder object with the tokens
finder = nltk.collocations.BigramCollocationFinder.from_words(tokens)
# build a dictionary with bigrams and their frequencies
bigram_measures = nltk.collocations.BigramAssocMeasures()
scored = dict(finder.score_ngrams(bigram_measures.raw_freq))
# build a word list
words = ['test', 'This']
# create the filter...
myfilter = create_filter_minfreq_inwords(scored, words, 0.1)
print 'Before filter:\n', list(finder.score_ngrams(bigram_measures.raw_freq))
# apply filter
finder.apply_ngram_filter(myfilter)
print '\nAfter filter:\n', list(finder.score_ngrams(bigram_measures.raw_freq))