gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 20:58:42 27 4
gpt4 key购买 nike

我正在使用 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\"~")

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

非常感谢您提前提供的帮助!

最佳答案

我知道该怎么做:

只需更改:

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

希望它可以帮助别人!

关于python - QueryParser.parse,限制单词之间的距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55840903/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com