首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >特定单词的NLTK搭配

特定单词的NLTK搭配
EN

Stack Overflow用户
提问于 2014-01-16 23:18:35
回答 3查看 10.8K关注 0票数 14

我知道如何使用NLTK获得二元语法和三元语法搭配,并将它们应用于我自己的语料库。代码如下。

然而,我不确定(1)如何获得特定单词的搭配?(2) NLTK是否有基于对数似然比的搭配度量?

代码语言:javascript
复制
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
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-01-17 19:54:31

尝试以下代码:

代码语言:javascript
复制
import nltk
from nltk.collocations import *
bigram_measures = nltk.collocations.BigramAssocMeasures()
trigram_measures = nltk.collocations.TrigramAssocMeasures()

# Ngrams with 'creature' as a member
creature_filter = lambda *w: 'creature' not in w


## Bigrams
finder = BigramCollocationFinder.from_words(
   nltk.corpus.genesis.words('english-web.txt'))
# only bigrams that appear 3+ times
finder.apply_freq_filter(3)
# only bigrams that contain 'creature'
finder.apply_ngram_filter(creature_filter)
# return the 10 n-grams with the highest PMI
print finder.nbest(bigram_measures.likelihood_ratio, 10)


## Trigrams
finder = TrigramCollocationFinder.from_words(
   nltk.corpus.genesis.words('english-web.txt'))
# only trigrams that appear 3+ times
finder.apply_freq_filter(3)
# only trigrams that contain 'creature'
finder.apply_ngram_filter(creature_filter)
# return the 10 n-grams with the highest PMI
print finder.nbest(trigram_measures.likelihood_ratio, 10)

它使用似然度量,并过滤掉不包含“生物”一词的Ngram

票数 13
EN

Stack Overflow用户

发布于 2014-01-17 12:22:02

问题1-尝试:

代码语言:javascript
复制
target_word = "electronic" # your choice of word
finder.apply_ngram_filter(lambda w1, w2, w3: target_word not in (w1, w2, w3))
for i in finder.score_ngrams(trigram_measures.likelihood_ratio):
print i

这个想法是过滤掉你不想要的东西。这种方法通常用于过滤掉ngram中特定部分的单词,您可以根据自己的需要进行调整。

票数 2
EN

Stack Overflow用户

发布于 2014-01-17 11:57:59

至于第二个问题,是的!NLTK在其关联度量中具有似然比。第一个问题仍然没有回答!

http://nltk.org/api/nltk.metrics.html?highlight=likelihood_ratio#nltk.metrics.association.NgramAssocMeasures.likelihood_ratio

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21165702

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档