Xapian 初体验之 hello xapian

文件夹结构:

~/helloxapian

~/helloxapian/indexfiles.py

~/helloxapian/search.py

~/helloxapian/test

~/helloxapian/test/hello.txt

~/helloxapian/test/world.txt

~/helloxapian/test/abc.txt

hello.txt文件内容:

world.txt文件内容:

abc.txt文件内容:

indexfiles.py文件:

#!/usr/bin/env python

#coding=utf-8

import sys

import xapian

import string

from os import listdir

import re

rex=re.compile('[a-zA-Z0-9]+') #给英文内容进行简单的分词,暂时不涉及中文

MAX_TERM_LENGTH = 64 #设置一个关键词的最大长度

DBPATH='indexdb' #索引文件目录

if len(sys.argv) < 2:

try:

except Exception, e:

现在打开终端窗口,到~/helloxapian目录中执行python indexfiles.py test 就可以把test目录下的所有.txt文件都建立索引。此时在~/helloxapian下会多出一个indexdb目录,这就是存储索引文件的目录。 search.py文件内容: #!/usr/bin/env python #coding=utf-8 import sys import xapian if len(sys.argv) < 2: print >> sys.stderr, "缺少参数,请提供要查询的关键词" sys.exit(1) DBPATH='indexdb' try: db = xapian.Database(DBPATH) #打开索引文件 enquire = xapian.Enquire(db) #Enquire类是负责执行查询的 stemmer = xapian.Stem('english') terms = [] for term in sys.argv[1:]: terms.append(stemmer(term.lower())) #将命令行参数中的所有关键词添加到要查找的关键词列表中 query = xapian.Query(xapian.Query.OP_OR,terms) #Query是查找条件类,OP_OR说明各关键词之关的组合关系,还有OP_AND等等 enquire.set_query(query) #设置查询条件 mset=enquire.get_mset(0,10) #获取前十条结果 print '共搜索到结果:' + str(mset.get_matches_estimated()) for match in mset: doc=match[xapian.MSET_DOCUMENT]#得到一个Docuemnt对像 print '=========\r\n文件名:%s\r\n摘要:%s...' % (doc.get_value(0),doc.get_data()[:80]) # except Exception, e: print >> sys.stderr, "Exception: %s" % str(e) sys.exit(1)