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 相关文章推荐
python抓取网页图片示例(python爬虫)
Apr 27 Python
Linux下使用python自动修改本机网关代码分享
May 21 Python
django轻松使用富文本编辑器CKEditor的方法
Mar 30 Python
python在ubuntu中的几种安装方法(小结)
Dec 08 Python
Python多线程threading和multiprocessing模块实例解析
Jan 29 Python
python批量设置多个Excel文件页眉页脚的脚本
Mar 14 Python
mac 安装python网络请求包requests方法
Jun 13 Python
Django页面数据的缓存与使用的具体方法
Apr 23 Python
使用Python实现跳帧截取视频帧
May 31 Python
Python读取VOC中的xml目标框实例
Mar 10 Python
使用keras实现densenet和Xception的模型融合
May 23 Python
python实现计算器简易版
Dec 17 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
php xml常用函数的集合(比较详细)
2013/06/06 PHP
使用Discuz关键词服务器实现PHP中文分词
2014/03/11 PHP
浅析php工厂模式
2014/11/25 PHP
Laravel多用户认证系统示例详解
2018/03/13 PHP
javascript中的关于类型转换的性能优化
2010/12/14 Javascript
JQuery模板插件 jquery.tmpl 动态ajax扩展
2011/11/10 Javascript
手把手教你使用vue-cli脚手架(图文解析)
2017/11/08 Javascript
angular2路由之routerLinkActive指令【推荐】
2018/05/30 Javascript
JS使用Prim算法和Kruskal算法实现最小生成树
2019/01/17 Javascript
解决Layui中templet中a的onclick参数传递的问题
2019/09/20 Javascript
vue cli3 配置proxy代理无效的解决
2019/10/30 Javascript
jQuery实现鼠标移入显示蒙版效果
2020/01/11 jQuery
js实现简单音乐播放器
2020/06/30 Javascript
Vue 解决在element中使用$notify在提示信息中换行问题
2020/11/11 Javascript
python 生成目录树及显示文件大小的代码
2009/07/23 Python
教你学会使用Python正则表达式
2017/09/07 Python
python中set()函数简介及实例解析
2018/01/09 Python
Python基于pycrypto实现的AES加密和解密算法示例
2018/04/10 Python
对pandas中to_dict的用法详解
2018/06/05 Python
Python计算开方、立方、圆周率,精确到小数点后任意位的方法
2018/07/17 Python
pygame游戏之旅 添加碰撞效果的方法
2018/11/20 Python
python对验证码降噪的实现示例代码
2019/11/12 Python
ubuntu 安装pyqt5和卸载pyQt5的方法
2020/03/24 Python
Python中免验证跳转到内容页的实例代码
2020/10/23 Python
Python之qq自动发消息的示例代码
2021/02/18 Python
毕业学生推荐信
2013/12/01 职场文书
《会走路的树》教后反思
2014/04/19 职场文书
个人评语大全
2014/05/04 职场文书
教师师德演讲稿
2014/05/06 职场文书
环保倡议书100字
2014/05/15 职场文书
会计专业自荐信
2014/06/03 职场文书
教代会开幕词
2015/01/28 职场文书
长城导游词
2015/01/30 职场文书
环卫个人总结
2015/03/03 职场文书
2015年学校远程教育工作总结
2015/07/20 职场文书
小学美术教学反思
2016/02/17 职场文书