PyLucene實戰

jopen 12年前發布 | 41K 次閱讀 PyLucene 搜索引擎

PyLuceneJavaLucenePython版封裝。這個工具的目標是讓Python使用Lucene的文本索引和搜索能力。它與JavaLucene的最新版本是兼容的。PyLucene把一個帶有JAVA VMLucene嵌入到Python進程中。你可以在http://lucene.apache.org/pylucene/網站上找到更多的PyLucene詳情。

本文中,我們將描述如何使用PyLucene構建搜索索引和查詢一個搜索索引。你可以從先前的文檔看到Lucene3.0安裝說明

PyLucene-Win32下的安裝包可以從下面的網址中找到:

http://code.google.com/a/apache-extras.org/p/pylucene-extra/downloads/list

注:使用PyLucene必須安裝Java SDK

1.  使用PyLucene創建索引

使用下面的代碼基于PyLucene來創建索引

#!/usr/bin/env python

 import os,sys,glob

 import lucene

 fromlucene import SimpleFSDirectory, System, File, Document, Field, \

 StandardAnalyzer, IndexWriter, Version

 """

 Example of Indexing with PyLucene 3.0

 """

def luceneIndexer(docdir,indir):

         """

         IndexDocuments from a directory

         """

         lucene.initVM()

         DIRTOINDEX= docdir

         INDEXIDR= indir

         indexdir= SimpleFSDirectory(File(INDEXIDR))

         analyzer= StandardAnalyzer(Version.LUCENE_30)

         index_writer= IndexWriter(indexdir,analyzer,True,\

         IndexWriter.MaxFieldLength(512))

         fortfile in glob.glob(os.path.join(DIRTOINDEX,'*.txt')):

                   print"Indexing: ", tfile

                   document= Document()

                   content= open(tfile,'r').read()

                   document.add(Field("text",content,Field.Store.YES,\

                            Field.Index.ANALYZED))

                   index_writer.addDocument(document)

                   print"Done: ", tfile

         index_writer.optimize()

         printindex_writer.numDocs()

         index_writer.close()

你必須提供兩個參數給luceneIndexer()函數。

1)  一個保存被索引文檔的目錄路徑;

2)  一個索引存儲的目錄路徑。

2.  使用Pylucene查詢

下面的代碼用于查詢Pylucene創建的索引。

#!/usr/bin/env python

 import sys

 import lucene

 fromlucene import SimpleFSDirectory, System, File, Document, Field,\

 StandardAnalyzer, IndexSearcher, Version,QueryParser

 """

 PyLucene retriver simple example

 """

 INDEXDIR = "./MyIndex"

def luceneRetriver(query):

         lucene.initVM()

         indir= SimpleFSDirectory(File(INDEXDIR))

         lucene_analyzer= StandardAnalyzer(Version.LUCENE_30)

         lucene_searcher= IndexSearcher(indir)

         my_query= QueryParser(Version.LUCENE_30,"text",\

         lucene_analyzer).parse(query)

         MAX= 1000

total_hits =lucene_searcher.search(my_query,MAX)

         print"Hits: ",total_hits.totalHits

         forhit in total_hits.scoreDocs:

                   print"Hit Score: ",hit.score, "Hit Doc:",hit.doc, "HitString:",hit.toString()

                   doc= lucene_searcher.doc(hit.doc)

                   printdoc.get("text").encode("utf-8")

 luceneRetriver("really coolrestaurant")

在代碼中,我們認為的指定索引目錄為INDEXDIR=./MyIndex,你也可以使用命令行參數(sys.argv)來接收索引目錄來替換它。

當使用函數luceneRetriver()時,你必須給一個查詢作為參數。

轉自:http://blog.csdn.net/fan_hai_ping/article/details/7966461

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!