QueryParser.parse,限制单词之间的距离

时间:2019-04-25 02:15:55

标签: python python-3.x whoosh fuzzy

我正在使用whoosh软件包进行全文模糊匹配。

我当前的代码如下:

from whoosh.index import create_in
from whoosh.fields import *
from whoosh.query import FuzzyTerm


class MyFuzzyTerm(FuzzyTerm):
    def __init__(self, fieldname, text, boost=1.0, maxdist=2, prefixlength=1, constantscore=True):
        super(MyFuzzyTerm, self).__init__(fieldname, text, boost, maxdist, prefixlength, constantscore)


if not os.path.exists("indexdir"):
    os.mkdir("indexdir")

path = u"MMM2.txt"
content = open('MMM2.txt', 'r').read()

schema = Schema(name=TEXT(stored=True), content=TEXT)
ix = create_in("indexdir", schema)
writer = ix.writer()
writer.add_document(name=path, content= content)
writer.commit()

from whoosh.qparser import QueryParser, FuzzyTermPlugin, PhrasePlugin, SequencePlugin

with ix.searcher() as searcher:
    parser = QueryParser(u"content", ix.schema,termclass = MyFuzzyTerm)
    parser.add_plugin(FuzzyTermPlugin())
    parser.remove_plugin_class(PhrasePlugin)
    parser.add_plugin(SequencePlugin())
    str = u"Tennessee Riverkeeper Inc"
    query = parser.parse(str)
    # query = parser.parse(u"\"Tennessee Riverkeeper Inc\"~")
    results = searcher.search(query)
    print ("nb of results =", len(results),results, type(results))
    for r in results:
        print (r)

在文件MMM2.txt中,它包含以下文本:“ Tennessee aa Riverkeeper aa aa Inc”。理想情况下,我希望程序返回0,因为我想将术语中的单词之间的距离限制在1以内。但是,它仍然返回:

nb of results = 1 <Top 1 Results for And([MyFuzzyTerm('content', 'tennessee', boost=1.000000, maxdist=2, prefixlength=1), MyFuzzyTerm('content', 'riverkeeper', boost=1.000000, maxdist=2, prefixlength=1), MyFuzzyTerm('content', 'inc', boost=1.000000, maxdist=2, prefixlength=1)]) runtime=0.009658594451408662> <class 'whoosh.searching.Results'>
<Hit {'name': 'MMM2.txt'}>

但是,如果我替换:

query = parser.parse(str)

具有:

query = parser.parse(u"\"Tennessee Riverkeeper Inc\"~")

它按我想返回不匹配结果的方式工作。我想这与“〜”有关。但是,当我将字符串替换为变量名时,无法添加它。由于我要匹配的字符串太多,因此无法一一键入。每次循环时,我只能将它们存储到变量中。有什么办法可以解决这个问题?

非常感谢您的提前帮助!

1 个答案:

答案 0 :(得分:0)

我知道该怎么做

只是改变:

query = parser.parse('"%s"~' % str)

希望它可以帮助某人!