[英]The whoosh can not search the key word successfully
1.我正在寫一個非常簡單的 whoosh 項目。 首先,我讀取一個 txt 文件並使用 read() 方法獲取 txt 文件中的所有內容。 然后為這個內容建立一個索引。
2.實現代碼如下:
對於txt文件內容:
#import functions from whoosh
import whoosh
from whoosh.index import create_in
from whoosh.fields import *
from whoosh.qparser import QueryParser
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT)
ix = create_in(".", schema)
writer = ix.writer()
i = 0
f = open("read.txt", "r")
print(f.read())
writer.add_document(title=u"document "+str(i), path=u".",content=f.read()) #python iterator i starting from 0
writer.commit(optimize=True)
searcher = ix.searcher()
parser = QueryParser("content", ix.schema)
stringquery = parser.parse("Hello")
results = searcher.search(stringquery)
print ("search 1 result:")
print (results)
for r in results:
print (r)
對於txt文件內容:
Hello this is the test
I hope you are doing well
I think you can do it without problem
This is so cool without funciton
'Hello' 假設存儲在索引中,但是當我嘗試搜索 hello 時,它什么也不返回
search 1 result:
<Top 0 Results for Term('content', 'hello') runtime=7.878600001731684e-05>
您的第一次調用f.read()
打印文件中的文本,下一次調用f.read()
沒有可讀取的內容並且不返回任何內容。 存儲文本。
file_content = f.read()
print(file_content)
writer.add_document(title=u"document "+str(i), path=u".", content=file_content)
為了進一步證明,
$ cat test.txt
Hello this is the test
I hope you are doing well
I think you can do it without problem
This is so cool without funciton
$ ipython
Python 3.9.0 (default, Dec 2 2020, 10:34:08)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: f = open("test.txt", "r")
In [2]: print(f.read())
Hello this is the test
I hope you are doing well
I think you can do it without problem
This is so cool without funciton
In [3]: print(f.read())
In [4]: quit
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.