【问题标题】:How to find bi-grams which include pre-defined words?如何找到包含预定义单词的二元组?
【发布时间】:2019-05-19 06:24:42
【问题描述】:

我知道可以从以下链接的示例中找到具有特定单词的二元组:

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"] 如何获得给定单词的二元组列表。 IE: [("yesterday", "I"), ("other", "side")]?

【问题讨论】:

    标签: python nlp nltk


    【解决方案1】:

    你想要的可能是一个 word_filter 函数,它仅在特定二元组中的所有单词都是列表的一部分时才返回 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 进行任何更改

    【讨论】:

    • 感谢您的回答@Mortz。我不想从列表中找到所有二元组的组合。更准确地说,我正在寻找一种方法来查找包含给定列表中两个单词的文本中的所有二元组。
    • 当你说“两个词”时,你的意思是说你也想考虑,比如,(" yesterday ", " side") 作为一个有效的二元组吗?
    • 是的,完全正确。这就是我的意思。
    • 是的,虽然我创建了一个包含所有二元组的元组列表并循环遍历它们,但没有使用函数,每次检查二元组的两个单词是否都在单词列表中并删除无效的单词.
    • 从搜索列表创建二元组列表的唯一问题是,一旦您的搜索列表开始变大,创建二元组列表的计算量就会开始增加。始终最好在内置函数中使用
    【解决方案2】:

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

    然后,您根据 countVectorizer 给出的计数过滤生成的二元组。

    注意:我已更改标记模式以考虑单个字符。默认情况下,它会跳过单个字符。

    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']
    

    当您拥有更多文档而词汇表中的单词数量更少时,这种方法将是一种更好的方法。如果反过来,您可以先找到文档中的所有二元组,然后使用您的词汇表对其进行过滤。

    【讨论】:

      猜你喜欢
      • 2018-08-18
      • 2021-04-23
      • 1970-01-01
      • 2012-05-20
      • 1970-01-01
      • 1970-01-01
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多