如何使用gensim.similarities.Similarity查找两个句子之间的相似性

时间:2018-07-11 14:05:08

标签: python python-3.x nltk gensim corpus

我想编写代码以查找两个句子之间的相似性,然后最终使用nltk和gensim编写此代码。我使用了标记化和gensim.similarities.Similarity来完成这项工作。但这没有达到我的目的。 在介绍最后一行代码之前,它工作正常。

import gensim
import nltk

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."]
from nltk.tokenize import word_tokenize
gen_docs = [[w.lower() for w in word_tokenize(text)]
        for text in raw_documents]



dictionary = gensim.corpora.Dictionary(gen_docs)
print(dictionary[5])
print(dictionary.token2id['socks'])
print("Number of words in dictionary:",len(dictionary))
for i in range(len(dictionary)):
    print(i, dictionary[i])

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

tf_idf = gensim.models.TfidfModel(corpus)
print(tf_idf)
    s = 0
for i in corpus:
s += len(i)
print(s)

sims = gensim.similarities.Similarity('/usr/workdir/',tf_idf[corpus],
                                  num_features=len(dictionary))
print(sims)
print(type(sims))


query_doc = [w.lower() for w in word_tokenize("Socks are a force for good.")]
print(query_doc)
query_doc_bow = dictionary.doc2bow(query_doc)
print(query_doc_bow)
query_doc_tf_idf = tf_idf[query_doc_bow]
print(query_doc_tf_idf)

sims[query_doc_tf_idf]

它抛出此错误。我在互联网上的任何地方都找不到答案。

Traceback (most recent call last):
  File "C:\Python36\lib\site-packages\gensim\utils.py", line 679, in save
_pickle.dump(self, fname_or_handle, protocol=pickle_protocol)
TypeError: file must have a 'write' attribute

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "semantic.py", line 45, in <module>
    sims[query_doc_tf_idf]
  File "C:\Python36\lib\site-packages\gensim\similarities\docsim.py", line 
503, in __getitem__
    self.close_shard()  # no-op if no documents added to index since last 
query
 File "C:\Python36\lib\site-packages\gensim\similarities\docsim.py", line 
427, in close_shard
    shard = Shard(self.shardid2filename(shardid), index)
 File "C:\Python36\lib\site-packages\gensim\similarities\docsim.py", line 
110, in __init__
    index.save(self.fullname())
  File "C:\Python36\lib\site-packages\gensim\utils.py", line 682, in save
    self._smart_save(fname_or_handle, separately, sep_limit, ignore, 
pickle_protocol=pickle_protocol)
  File "C:\Python36\lib\site-packages\gensim\utils.py", line 538, in 
_smart_save
    pickle(self, fname, protocol=pickle_protocol)
  File "C:\Python36\lib\site-packages\gensim\utils.py", line 1337, in pickle
    with smart_open(fname, 'wb') as fout:  # 'b' for binary, needed on 
Windows
  File "C:\Python36\lib\site-packages\smart_open\smart_open_lib.py", line 
181, in smart_open
fobj = _shortcut_open(uri, mode, **kw)
  File "C:\Python36\lib\site-packages\smart_open\smart_open_lib.py", line 
287, in _shortcut_open
return io.open(parsed_uri.uri_path, mode, **open_kwargs)

请帮助找出问题所在。

1 个答案:

答案 0 :(得分:1)

如果您在实例化“相似性”时指定了有效路径,则您的查询应该可以使用。对于下面的示例,我在C驱动器上创建了目录相似性,并在函数调用中指定了目录路径和文件名。

sims = gensim.similarities.Similarity('C:/Similarity/sims',tf_idf[corpus],
                                  num_features=len(dictionary))
print(sims)
print(type(sims))

query_doc = [w.lower() for w in word_tokenize("Socks are a force for good.")]
print(query_doc)
query_doc_bow = dictionary.doc2bow(query_doc)
print(query_doc_bow)
query_doc_tf_idf = tf_idf[query_doc_bow]
print(query_doc_tf_idf)

print('Query result:', sims[query_doc_tf_idf])

Query result: [0.       0.84565616   0.      0.06124881   0.        ]