我知道,可以从下面的链接中找到具有特定单词的bigram:
finder = BigramCollocationFinder.from_words(text.split())
word_filter = lambda w1, w2: "man" not in (w1, w2)
finder.apply_ngram_filter(word_filter)
bigram_measures = nltk.collocations.BigramAssocMeasures()
raw_freq_ranking = finder.nbest(bigram_measures.raw_freq, 10) #top-10
>>> nltk: how to get bigrams containing a specific word
但我不知道如果我需要包含两个预先定义的词的比例表,如何应用这一点。
示例:
我的句子:"hello, yesterday I have seen a man walking. On the other side there was another man yelling: "who are you, man?"
给出一个列表:["yesterday", "other", "I", "side"],我如何才能得到一个双字母表与给定的词。即:[("yesterday", "I"), ("other", "side")]
发布于 2018-12-18 19:50:00
您想要的可能是一个word_filter函数,它只有在特定的bigram中的所有单词都是列表的一部分时才返回False。
def word_filter(x, y):
if x in lst and y in lst:
return False
return True其中lst = ["yesterday", "I", "other", "side"]
请注意,此函数正在从外部范围访问lst --这是一件危险的事情,因此请确保不对word_filter函数中的lst进行任何更改。
发布于 2018-12-19 16:59:41
首先,您可以为您的词汇表创建所有可能的bigram,并将其作为countVectorizer的输入,这可以将给定的文本转换为bigram计数。
然后,根据countVectorizer给出的计数过滤生成的bigram。
注意:我已经更改了标记模式,以说明即使是单个字符。默认情况下,它跳过单个字符。
from sklearn.feature_extraction.text import CountVectorizer
import itertools
corpus = ["hello, yesterday I have seen a man walking. On the other side there was another man yelling: who are you, man?"]
unigrams=["yesterday", "other", "I", "side"]
bi_grams=[' '.join(bi_gram).lower() for bi_gram in itertools.combinations(unigrams, 2)]
vectorizer = CountVectorizer(vocabulary=bi_grams,ngram_range=(2,2),token_pattern=r"(?u)\b\w+\b")
X = vectorizer.fit_transform(corpus)
print([word for count,word in zip(X.sum(0).tolist()[0],vectorizer.get_feature_names()) if count]) 产出:
['yesterday i', 'other side']当你在词汇表中有更多的文档和较少的单词时,这种方法将是一种更好的方法。如果相反,您可以先找到文档中的所有大写,然后使用词汇表对其进行过滤。
https://stackoverflow.com/questions/53839740
复制相似问题