scud(飛云小俠) http://www.jscud.com 轉載請注明來(lái)源/作者
關(guān)鍵字:lucene,html parser,全文檢索,IndexReader,Document,Field,IndexWriter,Term,HTMLPAGE
在使用lucene對相關(guān)內容進(jìn)行索引時(shí),會(huì )遇到各種格式的內容,例如Html,PDF,Word等等,那么我們如何從這么文檔中得到我們需要的內容哪?例如Html的內容,一般我們不需要對Html標簽建立索引,因為那不是我們需要搜索的內容.這個(gè)時(shí)候,我們就需要從Html內容中解析出我們所需要的內容.對于PDF,Word文檔,也是類(lèi)似的要求.
總之,我們只需要從內容中提取出我們需要的文本來(lái)建立索引,這樣用戶(hù)就能搜索到需要的內容,然后訪(fǎng)問(wèn)對應的資源即可.
Lucene本身帶的例子中有一個(gè)解析Html的代碼,不過(guò)不是純JAVA的,所以在網(wǎng)上我又找到了另外一個(gè)Html解析器,網(wǎng)址如下:http://htmlparser.sourceforge.net.
對PDF解析的相關(guān)項目有很多,例如PDFBox.在PDFBox里面提出pdf的文本內容只需要一句話(huà)即可:
| Document doc = LucenePDFDocument.getDocument( file ); |
/** //設置編碼:根據實(shí)際情況修改 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); //暫時(shí)不處理 meta OrFilter lastFilter = new OrFilter(); try //中場(chǎng)退出了 Node[] nodes = nodeList.toNodeArray(); String result = combineNodeText(nodes); //合并節點(diǎn)的有效內容 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(); |
| package com.jscud.www.support.search; /** * 搜索時(shí)解析Html后返回的頁(yè)面模型. * * @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; } } |
聯(lián)系客服