当关键字是多个单词时,可以有效地搜索关键字

苏西

我需要使用python有效地匹配字符串中很大的关键字列表(> 1000000)。我发现了一些非常好的库,它们试图快速地做到这一点:

1)FlashText(https://github.com/vi3k6i5/flashtext

2)Aho-Corasick算法等

但是,我有一个特殊的要求:在我的上下文中,如果我的字符串为“ XXXX是YYYY的一个很好的表示”,则关键字“ XXXX YYYY”应返回匹配项。请注意,此处'XXXX YYYY'不会作为子字符串出现,但是XXXX和YYYY存在于字符串中,这对我来说足够匹配了。

我知道如何天真地做。我要寻找的是效率,为此还需要其他更好的库吗?

aj

您的要求听起来像是全文搜索任务。有一个名为whoosh的Python搜索包可以像下面那样在内存中对@derek的主体进行索引和搜索。

from whoosh.filedb.filestore import RamStorage
from whoosh.qparser import QueryParser
from whoosh import fields


texts = [
    "Here's a sentence with dog and apple in it",
    "Here's a sentence with dog and poodle in it",
    "Here's a sentence with poodle and apple in it",
    "Here's a dog with and apple and a poodle in it",
    "Here's an apple with a dog to show that order is irrelevant"
]

schema = fields.Schema(text=fields.TEXT(stored=True))
storage = RamStorage()
index = storage.create_index(schema)
storage.open_index()

writer = index.writer()
for t in texts:
    writer.add_document(text = t)
writer.commit()

query = QueryParser('text', schema).parse('dog apple')
results = index.searcher().search(query)

for r in results:
    print(r)

这将产生:

<Hit {'text': "Here's a sentence with dog and apple in it"}>
<Hit {'text': "Here's a dog with and apple and a poodle in it"}>
<Hit {'text': "Here's an apple with a dog to show that order is irrelevant"}>

您还可以FileStorage按照如何建立文档索引中所述使用持久化索引

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章