使用Lucene進行全文檢索(二)---得到有效的內容(轉載)
在使用lucene對相關內容進行索引時,會遇到各種格式的內容,例如html,pdf,word等等,那麼我們如何從這麼文件中得到我們需要的內容哪?例如html的內容,一般我們不需要對html標籤建立索引,因為那不是我們需要搜尋的內容.這個時候,我們就需要從html內容中解析出我們所需要的內容.對於pdf,word文件,也是類似的要求.
總之,我們只需要從內容中提取出我們需要的文字來建立索引,這樣使用者就能搜尋到需要的內容,然後訪問對應的資源即可.
lucene本身帶的例子中有一個解析html的程式碼,不過不是純java的,所以在網上我又找到了另外一個html解析器,網址如下:http://htmlparser.sourceforge.net.
對pdf解析的相關專案有很多,例如pdfbox.在pdfbox裡面提出pdf的文字內容只需要一句話即可:
document doc = lucenepdfdocument.getdocument( file ); |
當然如果需要更高階的設定,就要使用pdfbox中pdftextstripper等類來實現更高階的操作了.
對word文件解析的相關有poi,網址是 http://jakarta.apache.org/poi/.
htmlparser本身提供的功能很強大,我們下面主要來關注我們需要的功能.首先給出幾個函式如下:
/** //設定編碼:根據實際情況修改 htmlpage visitor = new htmlpage(myparser); myparser.visitallnodeswith(visitor); title = visitor.gettitle(); body = combinenodetext(visitor.getbody().tonodearray()); searchhtmlpage result = new searchhtmlpage(title, body); return result; /** myparser = parser.createparser(content, "gbk"); nodefilter textfilter = new nodeclassfilter(textnode.class); //暫時不處理 meta orfilter lastfilter = new orfilter(); try //中場退出了 node[] nodes = nodelist.tonodearray(); string result = combinenodetext(nodes); //合併節點的有效內容 for (int i = 0; i < nodes.length; i++) string line = ""; line = linknode.getlink(); if (stringfunc.istrimempty(line)) continue; result.append(" ").append(line); return result.tostring(); |
其中searchhtmlpage類是表示一個html頁面的模型,包含標題和內容,程式碼如下:
package com.jscud.www.support.search; /** * 搜尋時解析html後返回的頁面模型. * * @author scud(飛雲小俠) http://www.jscud.com * */ public class searchhtmlpage { /**標題*/ private string title; /**內容*/ private string body; public searchhtmlpage(string title, string body) { this.title = title; this.body = body; } public string getbody() { return body; } public void setbody(string body) { this.body = body; } public string gettitle() { return title; } public void settitle(string title) { this.title = title; } } |
當然,使用htmlparser解析html資源還有很多其他的方法,可以設定很多的條件來滿足使用者的解析要求,使用者可以閱讀其他的文章或者htmlparser的文件來了解,在此不多介紹.
下一節講解如何進行搜尋.