使用 Python 中的 Whoosh 庫開發文字搜尋引擎


Whoosh 是一個 Python 庫,包含用於索引文字和搜尋索引的類和函式。假設您正在構建一個應用程式,需要遍歷各種文件,然後根據一些預定義的條件查詢相似之處或從中獲取資料,或者假設您想統計專案標題在研究論文中出現的次數,那麼本教程中構建的內容將非常有用。

入門

為了構建我們的文字搜尋引擎,我們將使用 Whoosh 庫。

此庫沒有預先打包到 Python 中。因此,我們將使用 pip 包管理器下載並安裝它。

要安裝 Whoosh 庫,請使用以下命令。

pip install whoosh

現在,我們可以使用以下命令將其匯入到我們的指令碼中。

from whoosh.fields import Schema, TEXT, ID
from whoosh import index

使用 Python 構建文字搜尋引擎

首先,讓我們定義一個資料夾,在需要時我們將把索引檔案儲存到該資料夾中。

import os.path
os.mkdir("dir")

接下來,讓我們定義一個模式。模式指定索引中文件的欄位。

schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(stored = True))
ind = index.create_in("dir", schema)
writer = ind.writer()
writer.add_document(title=u"doc", content=u"Py doc hello big world", path=u"/a") 
writer.commit()

現在我們已經索引了文件,我們對其進行搜尋。

from whoosh.qparser import QueryParser
with ind.searcher() as searcher:
     query = QueryParser("content", ind.schema).parse("hello world")
     results = searcher.search(query, terms=True)
     for r in results:
         print (r, r.score)
         if results.has_matched_terms():
            print(results.matched_terms())

輸出

它將產生以下輸出

<Hit {'path': '/a', 'title': 'doc', 'content': 'Py doc hello big world'}> 
1.7906976744186047
{('content', b'hello'), ('content', b'world')}

示例

以下是完整程式碼

from whoosh.fields import Schema, TEXT, ID
from whoosh import index
import os.path
os.mkdir("dir")
schema = Schema(title=TEXT(stored=True), path=ID(stored=True), content=TEXT(stored = True))
ind = index.create_in("dir", schema)
writer = ind.writer()
writer.add_document(title=u"doc", content=u"Py doc hello big world", path=u"/a") 
writer.commit()

from whoosh.qparser import QueryParser
with ind.searcher() as searcher:
     query = QueryParser("content", ind.schema).parse("hello world")
     results = searcher.search(query, terms=True)
     for r in results:
         print (r, r.score)
         if results.has_matched_terms():
            print(results.matched_terms())

結論

您現在已經學會了如何在 Python 中建立文字搜尋引擎。使用它,您可以在幾秒鐘內搜尋各種文件以提取有用的內容。您還探索了 Python 中 Whoosh 庫的潛力。

更新於: 2023年8月31日

980 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告