parse,限制单词之间的距离

2024-09-27 20:21:06 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

非常感谢您的帮助


Tags: fromimporttxtparsercontentqueryresultswriter

热门问题