【发布时间】:2014-06-04 01:19:22
【问题描述】:
我正在尝试返回两个文档之间的所有相似句子,我的解决方案有效,但速度极慢。有没有更有效的方法来做到这一点?
我打开两个文档(A 和 B),并使用 NLTK 将两个文档中的每个句子提取到 list_a 和 list_b 中(快速)。从那里,我遍历 list_a 中的每个句子,并将每个句子与 list_b 中的所有句子进行比较(慢)。如果两个句子在百分比上相似,我会将相似的句子附加到 results_list 以供稍后查看。
我用来比较两个句子的代码:
# Compare two sentences
def compare_sentences( sentences_a, sentences_b ):
# Init our vectorizer
vect = TfidfVectorizer( min_df = 1 )
# Create our tfidf
tfidf = vect.fit_transform( [ sentences_a, sentences_b ] )
# Get an array of results
results = ( tfidf * tfidf.T ).A
# Return percentage float
return float( '%.4f' % ( results[0][1] * 100 ) )
# end compare_sentences()
我已经看到许多有用的答案,描述了如何在一般意义上比较两个文档,但我想找到一个解决方案,提供两者之间所有相似句子的列表。
感谢您的帮助。
【问题讨论】:
-
不将 float-to-string-to-float 转换是第一个明显的优化。
标签: python scikit-learn nltk