python 全文检索引擎详解


Posted in Python onApril 25, 2017

python 全文检索引擎详解

最近一直在探索着如何用Python实现像百度那样的关键词检索功能。说起关键词检索,我们会不由自主地联想到正则表达式。正则表达式是所有检索的基础,python中有个re类,是专门用于正则匹配。然而,光光是正则表达式是不能很好实现检索功能的。

python有一个whoosh包,是专门用于全文搜索引擎。

whoosh在国内使用的比较少,而它的性能还没有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()

构建索引的函数

@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()

检索函数

@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

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

Python 相关文章推荐
Django 导出 Excel 代码的实例详解
Aug 11 Python
2018年Python值得关注的开源库、工具和开发者(总结篇)
Jan 04 Python
Python实现的径向基(RBF)神经网络示例
Feb 06 Python
对python的文件内注释 help注释方法
May 23 Python
python 给DataFrame增加index行名和columns列名的实现方法
Jun 08 Python
Flask框架Flask-Principal基本用法实例分析
Jul 23 Python
Python使用scrapy爬取阳光热线问政平台过程解析
Aug 14 Python
opencv实现简单人脸识别
Feb 19 Python
为什么黑客都用python(123个黑客必备的Python工具)
Jan 31 Python
Python如何实现爬取B站视频
May 20 Python
Django视图类型总结
Feb 17 Python
Python爬取网站图片并保存的实现示例
Feb 26 Python
window下eclipse安装python插件教程
Apr 24 #Python
Python处理PDF及生成多层PDF实例代码
Apr 24 #Python
python爬虫框架scrapy实战之爬取京东商城进阶篇
Apr 24 #Python
python爬虫实战之爬取京东商城实例教程
Apr 24 #Python
python中urllib.unquote乱码的原因与解决方法
Apr 24 #Python
Python面向对象特殊成员
Apr 24 #Python
Python解惑之整数比较详解
Apr 24 #Python
You might like
PHP4 与 MySQL 交互使用
2006/10/09 PHP
经典的PHPer为什么被认为是草根?
2007/04/02 PHP
php下使用SimpleXML 处理XML 文件
2010/02/27 PHP
php防止sql注入代码实例
2013/12/18 PHP
修改ThinkPHP缓存为Memcache的方法
2014/06/25 PHP
php web环境和命令行环境下查找php.ini的位置
2019/07/17 PHP
从零开始学习jQuery (十一) 实战表单验证与自动完成提示插件
2011/02/23 Javascript
jquery 简单应用示例总结
2013/08/09 Javascript
JS注释所产生的bug 即使注释也会执行
2013/11/19 Javascript
JavaScript实现将UPC转换成ISBN的方法
2015/05/26 Javascript
程序员必知35个jQuery 代码片段
2015/11/05 Javascript
基于JavaScript如何制作遮罩层对话框
2016/01/26 Javascript
详解JavaScript中数组的reduce方法
2016/12/02 Javascript
js编写简单的聊天室功能
2017/08/17 Javascript
vue 详情跳转至列表页实现列表页缓存
2019/03/27 Javascript
Vue使用.sync 实现父子组件的双向绑定数据问题
2019/04/04 Javascript
JavaScript实现的滚动公告特效【基于jQuery】
2019/07/10 jQuery
VUE路由动态加载实例代码讲解
2019/08/26 Javascript
[38:30]2014 DOTA2国际邀请赛中国区预选赛 LGD-GAMING VS CIS 第一场2
2014/05/24 DOTA
在Python中使用Mako模版库的简单教程
2015/04/08 Python
Python cookbook(数据结构与算法)同时对数据做转换和换算处理操作示例
2018/03/23 Python
浅谈Python编程中3个常用的数据结构和算法
2019/04/30 Python
Numpy 中的矩阵求逆实例
2019/08/26 Python
Django和Flask框架优缺点对比
2019/10/24 Python
PyQt5中多线程模块QThread使用方法的实现
2020/01/31 Python
python如何解析复杂sql,实现数据库和表的提取的实例剖析
2020/05/15 Python
深圳茁壮笔试题
2015/05/28 面试题
司机岗位职责
2013/11/15 职场文书
个人实用的自我评价范文
2013/11/23 职场文书
骨干教师培训制度
2014/01/13 职场文书
创新型城市实施方案
2014/03/06 职场文书
学习全国两会精神心得体会范文
2014/03/17 职场文书
葛优非诚勿扰搞笑征婚台词
2014/03/17 职场文书
个人授权委托书范本格式
2014/10/12 职场文书
2015年公路路政个人工作总结
2015/07/24 职场文书
讲解MySQL增删改操作
2022/05/06 MySQL