首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何找到包含预定义词的双字母表?

如何找到包含预定义词的双字母表?
EN

Stack Overflow用户
提问于 2018-12-18 19:22:10
回答 2查看 289关注 0票数 1

我知道,可以从下面的链接中找到具有特定单词的bigram:

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

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-12-18 19:50:00

您想要的可能是一个word_filter函数,它只有在特定的bigram中的所有单词都是列表的一部分时才返回False

代码语言:javascript
复制
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进行任何更改。

票数 1
EN

Stack Overflow用户

发布于 2018-12-19 16:59:41

首先,您可以为您的词汇表创建所有可能的bigram,并将其作为countVectorizer的输入,这可以将给定的文本转换为bigram计数。

然后,根据countVectorizer给出的计数过滤生成的bigram。

注意:我已经更改了标记模式,以说明即使是单个字符。默认情况下,它跳过单个字符。

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

产出:

代码语言:javascript
复制
['yesterday i', 'other side']

当你在词汇表中有更多的文档和较少的单词时,这种方法将是一种更好的方法。如果相反,您可以先找到文档中的所有大写,然后使用词汇表对其进行过滤。

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

https://stackoverflow.com/questions/53839740

复制
相关文章

相似问题

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