python 全文檢索引擎詳解
python 全文檢索引擎詳解
最近一直在探索著如何用Python實現(xiàn)像百度那樣的關(guān)鍵詞檢索功能。說起關(guān)鍵詞檢索,我們會不由自主地聯(lián)想到正則表達式。正則表達式是所有檢索的基礎(chǔ),python中有個re類,是專門用于正則匹配。然而,光光是正則表達式是不能很好實現(xiàn)檢索功能的。
python有一個whoosh包,是專門用于全文搜索引擎。
whoosh在國內(nèi)使用的比較少,而它的性能還沒有sphinx/coreseek成熟,不過不同于前者,這是一個純python庫,對python的愛好者更為方便使用。具體的代碼如下
安裝
輸入命令行 pip install whoosh
需要導入的包有:
fromwhoosh.index import create_in fromwhoosh.fields import * fromwhoosh.analysis import RegexAnalyzer fromwhoosh.analysis import Tokenizer,Token
中文分詞解析器
class ChineseTokenizer(Tokenizer): """ 中文分詞解析器 """ def __call__(self, value, positions=False, chars=False, keeporiginal=True, removestops=True, start_pos=0, start_char=0, mode='', **kwargs): assert isinstance(value, text_type), "%r is not unicode "% value t = Token(positions, chars, removestops=removestops, mode=mode, **kwargs) list_seg = jieba.cut_for_search(value) for w in list_seg: t.original = t.text = w t.boost = 0.5 if positions: t.pos = start_pos + value.find(w) if chars: t.startchar = start_char + value.find(w) t.endchar = start_char + value.find(w) + len(w) yield t def chinese_analyzer(): return ChineseTokenizer()
構(gòu)建索引的函數(shù)
@staticmethod def create_index(document_dir): analyzer = chinese_analyzer() schema = Schema(titel=TEXT(stored=True, analyzer=analyzer), path=ID(stored=True), content=TEXT(stored=True, analyzer=analyzer)) ix = create_in("./", schema) writer = ix.writer() for parents, dirnames, filenames in os.walk(document_dir): for filename in filenames: title = filename.replace(".txt", "").decode('utf8') print title content = open(document_dir + '/' + filename, 'r').read().decode('utf-8') path = u"/b" writer.add_document(titel=title, path=path, content=content) writer.commit()
檢索函數(shù)
@staticmethod def search(search_str): title_list = [] print 'here' ix = open_dir("./") searcher = ix.searcher() print search_str,type(search_str) results = searcher.find("content", search_str) for hit in results: print hit['titel'] print hit.score print hit.highlights("content", top=10) title_list.append(hit['titel']) print 'tt',title_list return title_list
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
樹莓派上利用python+opencv+dlib實現(xiàn)嘴唇檢測的實現(xiàn)
本文主要介紹了樹莓派上利用python+opencv+dlib實現(xiàn)嘴唇檢測的實現(xiàn),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10使用memory_profiler監(jiān)測python代碼運行時內(nèi)存消耗方法
今天小編就為大家分享一篇使用memory_profiler監(jiān)測python代碼運行時內(nèi)存消耗方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-12-12python數(shù)據(jù)分析matplotlib的基礎(chǔ)繪圖使用
這篇文章主要為大家介紹了python數(shù)據(jù)分析matplotlib的基礎(chǔ)繪圖使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05python?pandas數(shù)據(jù)處理教程之合并與拼接
在實際處理數(shù)據(jù)業(yè)務(wù)需求中,我們經(jīng)常會遇到這樣的需求,將多個表連接起來再進行數(shù)據(jù)的處理和分析,類似SQL中的連接查詢功能,下面這篇文章主要給大家介紹了關(guān)于python?pandas數(shù)據(jù)處理教程之合并與拼接的相關(guān)資料,需要的朋友可以參考下2022-02-02