如何在 whoosh 上突出显示搜索
How to get highlighted searches on whoosh
我使用了 pythonhosted.org 中的示例代码,但似乎没有任何反应。这是我使用的代码:
results = mysearcher.search(myquery)
for hit in results:
print(hit["title"])
我将此代码输入 python,但它给出了一个错误 mysearcher is not defined
。所以我真的不确定我是否遗漏了一些东西,因为我只是想获得让我振作起来的基础知识 运行。
您没有定义搜索器mysearcher
,复制整个代码。这是一个完整的例子:
>>> import whoosh
>>> from whoosh.index import create_in
>>> from whoosh.fields import *
>>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
>>> ix = create_in("indexdir", schema)
>>> writer = ix.writer()
>>> writer.add_document(title=u"First document", path=u"/a",
... content=u"This is the first document we've added!")
>>> writer.add_document(title=u"Second document", path=u"/b",
... content=u"The second one is even more interesting!")
>>> writer.commit()
>>> from whoosh.qparser import QueryParser
>>> with ix.searcher() as searcher:
... query = QueryParser("content", ix.schema).parse("first")
... results = searcher.search(query)
... results[0]
...
{"title": u"First document", "path": u"/a"}
你可以这样突出显示:
for hit in results:
print(hit["title"])
# Assume "content" field is stored
print(hit.highlights("content"))
我使用了 pythonhosted.org 中的示例代码,但似乎没有任何反应。这是我使用的代码:
results = mysearcher.search(myquery)
for hit in results:
print(hit["title"])
我将此代码输入 python,但它给出了一个错误 mysearcher is not defined
。所以我真的不确定我是否遗漏了一些东西,因为我只是想获得让我振作起来的基础知识 运行。
您没有定义搜索器mysearcher
,复制整个代码。这是一个完整的例子:
>>> import whoosh
>>> from whoosh.index import create_in
>>> from whoosh.fields import *
>>> schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
>>> ix = create_in("indexdir", schema)
>>> writer = ix.writer()
>>> writer.add_document(title=u"First document", path=u"/a",
... content=u"This is the first document we've added!")
>>> writer.add_document(title=u"Second document", path=u"/b",
... content=u"The second one is even more interesting!")
>>> writer.commit()
>>> from whoosh.qparser import QueryParser
>>> with ix.searcher() as searcher:
... query = QueryParser("content", ix.schema).parse("first")
... results = searcher.search(query)
... results[0]
...
{"title": u"First document", "path": u"/a"}
你可以这样突出显示:
for hit in results:
print(hit["title"])
# Assume "content" field is stored
print(hit.highlights("content"))