如何从文档中查找和打印不匹配/不相似的单词?

时间:2019-02-11 09:05:05

标签: python scikit-learn nltk gensim

我正在尝试重写一种算法,该算法基本上需要一个输入文本文件,并与不同的文档进行比较并得出相似性。

现在我要打印不匹配单词的输出,并输出一个不匹配单词的新纺织品。

从此代码中,“ hello force”是输入,并针对raw_documents进行检查,并在0-1之间打印出匹配文档的等级(单词“ force”与第二个文档匹配,输出给第二个文档更多的等级,但是“ hello”不在任何raw_document中,我想将不匹配的单词“ hello”打印为不匹配),但是我要打印的是与任何raw_document都不匹配的不匹配输入单词

import gensim
import nltk

from nltk.tokenize import word_tokenize

raw_documents = ["I'm taking the show on the road",
                 "My socks are a force multiplier.",
             "I am the barber who cuts everyone's hair who doesn't 
cut their own.",
             "Legend has it that the mind is a mad monkey.",
            "I make my own fun."]

gen_docs = [[w.lower() for w in word_tokenize(text)]
            for text in raw_documents]

dictionary = gensim.corpora.Dictionary(gen_docs)

corpus = [dictionary.doc2bow(gen_doc) for gen_doc in gen_docs]

tf_idf = gensim.models.TfidfModel(corpus)
s = 0
for i in corpus:
    s += len(i)
sims =gensim.similarities.Similarity('/usr/workdir/',tf_idf[corpus],
                                  num_features=len(dictionary))
query_doc = [w.lower() for w in word_tokenize("hello force")]

query_doc_bow = dictionary.doc2bow(query_doc)

query_doc_tf_idf = tf_idf[query_doc_bow]
result = sims[query_doc_tf_idf] 
print result

1 个答案:

答案 0 :(得分:0)

如果您只是想知道单词'hello'不在其他文档中,则可能甚至不需要像gensim这样的自然语言帮助程序库。您可以只记录所有看到的单词,为此,一个普通的Python dictsetCounter就足够了。 (在将所有单词加载完毕后,只需依次检查新文本中的每个单词即可。)

Gensim的TfidfModelSimilarity的比较。处理相对微妙的相对度(不是单词存在的“是/否”)。

而且,gensim.corpora.Dictionary.doc2bow()方法通常会忽略字典中不为人知的单词-因为它们没有分配空位,因此可能稀有/不重要-而不是将它们包括在返回的数据中。因此,默认情况下它返回的“单词袋”表示形式(实际上是(known_word_index, count)的列表)无法帮助简单地对尚未发现的单词进行尚未发现的检测。

但是,您可以查看其可选的return_missing参数,并请求return_missing=True。然后,它返回一个(bag_of_words,dict_of_missing_words)元组-通过查看该第二个返回值,可以查看gensim.corpora.Dictionary对象中已经没有的单词。参见:

https://radimrehurek.com/gensim/corpora/dictionary.html#gensim.corpora.dictionary.Dictionary.doc2bow