1. 程式人生 > 程式設計 >使用python+whoosh實現全文檢索

使用python+whoosh實現全文檢索

whoosh的官方介紹:http://whoosh.readthedocs.io/en/latest/quickstart.html

因為做的是中文的全文檢索需要匯入jieba工具包以及whoosh工具包

直接上程式碼吧

from whoosh.qparser import QueryParser 
from whoosh.index import create_in 
from whoosh.index import open_dir 
from whoosh.fields import * 
from jieba.analyse import ChineseAnalyzer 
from get_comment import SQL 
from whoosh.sorting import FieldFacet 
 
analyser = ChineseAnalyzer()  #匯入中文分詞工具 
schema = Schema(phone_name=TEXT(stored=True,analyzer=analyser),price=NUMERIC(stored=True),phoneid=ID(stored=True))# 建立索引結構 
ix = create_in("path",schema=schema,indexname='indexname') #path 為索引建立的地址,indexname為索引名稱 
writer = ix.writer() 
writer.add_document(phone_name='name',price ="price",phoneid ="id") # 此處為新增的內容  
print("建立完成一個索引") 
writer.commit() 
# 以上為建立索引的過程 
new_list = [] 
index = open_dir("indexpath",indexname='comment') #讀取建立好的索引 
with index.searcher() as searcher: 
  parser = QueryParser("要搜尋的專案,比如“phone_name",index.schema) 
  myquery = parser.parse("搜尋的關鍵字") 
  facet = FieldFacet("price",reverse=True) #按序排列搜尋結果 
  results = searcher.search(myquery,limit=None,sortedby=facet) #limit為搜尋結果的限制,預設為10,詳見部落格開頭的官方文件 
  for result1 in results: 
    print(dict(result1)) 
    new_list.append(dict(result1))

注:

Whoosh 有一些很有用的預定義 field types,你也可以很easy的建立你自己的。

whoosh.fields.ID

這個型別簡單地將field的值索引為一個獨立單元(這意味著,他不被分成單獨的單詞)。這對於檔案路徑、URL、時間、類別等field很有益處。

whoosh.fields.STORED

這個型別和文件儲存在一起,但沒有被索引。這個field type不可搜尋。這對於你想在搜尋結果中展示給使用者的文件資訊很有用。

whoosh.fields.KEYWORD

這個型別針對於空格或逗號間隔的關鍵詞設計。可索引可搜尋(部分儲存)。為減少空間,不支援短語搜尋。

whoosh.fields.TEXT

這個型別針對文件主體。儲存文字及term的位置以允許短語搜尋。

whoosh.fields.NUMERIC

這個型別專為數字設計,你可以儲存整數或浮點數。

whoosh.fields.BOOLEAN

這個型別儲存bool型

whoosh.fields.DATETIME

這個型別為 datetime object而設計(更多詳細資訊)

whoosh.fields.NGRAM 和 whoosh.fields.NGRAMWORDS

這些型別將fiel文字和單獨的term分成N-grams(更多Indexing & Searching N-grams的資訊)

以上這篇使用python+whoosh實現全文檢索就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。