语义搜索——从一堆文本文件中检索与传入的搜索短语非常匹配的句子

Semantic search - retrieve sentences from a bunch of text files that closely matches the passed in search phrase

我有一堆文本文件。我的应用要求是搜索与我传递的搜索短语在语义上匹配的句子(或段落)。

例如:假设有一个句子"The quick brown fox jumped over the lazy dog"。

我想要以下搜索短语来搜索我的文本文件并列出上面的句子(有时连同上一句和下一句以显示上下文)

(这通常是他们所说的在专利搜索网站中用于根据搜索词组识别专利的内容——语义搜索)

为了实现 - 我在网上查了一下,这是我发现的:

  1. 使用 nltk python 库中的句子分词器将文本文件分解成句子:
from nltk.tokenize import sent_tokenize 
f = open("fileName")
mytext = f.readline()
sent_tokenize(mytext)
  1. 需要等效于弹性搜索的匹配功能,如上传递搜索短语实际上会找到我要查找的句子。

请建议我使用一些库实现 1 和 2 的简单方法。此应用程序仅在我的机器上本地运行。

依赖关系:

pip install autocorrect

代码(search.py):

from autocorrect import spell
def lcs(X, Y):
    mat = []
    for i in range(0,len(X)):
        row = []
        for j in range(0,len(Y)):
            if X[i] == Y[j]:
                if i == 0 or j == 0:
                    row.append(1)
                else:
                    val = 1 + int( mat[i-1][j-1] )
                    row.append(val)
            else:
                row.append(0)
        mat.append(row)
    new_mat = []
    for r in  mat:
        r.sort()
        r.reverse()
        new_mat.append(r)
    lcs = 0
    for r in new_mat:
        if lcs < r[0]:
            lcs = r[0]
    return lcs
def spellCorrect(string):
    words = string.split(" ")
    correctWords = []
    for i in words:
        correctWords.append(spell(i))
    return " ".join(correctWords)
def semanticSearch(searchString, searchSentencesList):
    result = None
    searchString = spellCorrect(searchString)
    bestScore = 0
    for i in searchSentencesList:
        score = lcs(searchString, i)
        if score > bestScore:
            bestScore = score
            result = i
    return result


result = semanticSearch("fox jump over dog", ["The quick brown fox jumped over the lazy dog", "This is one more string which contains fox bron"])
print result