码迷,mamicode.com
首页 > 其他好文 > 详细

全文索引搜索whoosh(2)

时间:2014-07-12 20:22:08      阅读:342      评论:0      收藏:0      [点我收藏+]

标签:python   algorithm   中文分词   

承接前面对whoosh的文章,继续:


写索引文件


下面开始写入索引内容,过程如下:

writer = ix.writer()
writer.add_document(title=u"my document", content=u"this is my document", path=u"/a", tags=u"firlst short", icon=u"/icons/star.png")
writer.add_document(title=u"my second document", content=u"this is my second document", path=u"/b", tags=u"second short", icon=u"/icons/sheep.png")
writer.commit()

特别注意:

  • 字段的值必须是unicode类型
  • 不是每个字段都必须赋值

更多的内容,请参考:如何索引文件官方文档


搜索


开始搜索,需要新建立一个对象,如:

searcher = ix.searcher()

一般来讲,不是这么简单地,建立对象相当于开始搜索,完事之后要关闭,所以在实战中,常常写成:

withe ix.searcher() as searcher:
(do somthing)

或者写成(与上面的等效):

try:
    searcher = ix.searcher()
    (do somthing)
finally:
    searcher.close()

接下来就开始搜索了,以搜索content为例:

from whoosh.qparser import QueryParser
with ix.searcher() as searcher:
    query = QueryParser("content",ix.schema).parse("second")
    result = searcher.search(query)
    results[0]

返回显示:

{"title":u"my second document","path":u"/a"}

前面已经将上述两个字段设置为stored=True.


whoosh与结巴分词

原计划写这个相关代码,但是google之后,发现阿小信的博客(恕我不能给出链接,因为只要有链接,本文就不能发布,在我的github中是完整的,这里是阉割版)中有非常完美的解决,我特地将那段代码抄下来,供需要者参考:

#-*- coding:utf-8 -*-
import jieba
from whoosh.analysis import Tokenizer,Token 
from whoosh.compat import text_type

class ChineseTokenizer(Tokenizer):  
    def __call__(self, value, positions=False, chars=False,  
                 keeporiginal=False, 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)  
        seglist=jieba.cut_for_search(value)                       #使用结巴分词库进行分词  
        for w in seglist:  
            t.original = t.text = w  
            t.boost = 1.0  
            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                                               #通过生成器返回每个分词的结果token

def ChineseAnalyzer():  
    return ChineseTokenizer()

声明


本文属于阉割之后的版本。要看完整版,请到我的github:qiwsir的algorithm。

全文索引搜索whoosh(2),布布扣,bubuko.com

全文索引搜索whoosh(2)

标签:python   algorithm   中文分词   

原文地址:http://blog.csdn.net/qiwsir/article/details/37697651

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!