nutch作为一个完整的搜索引擎,是广大搜索爱好者学习的一个好项目。然而,因为nutch自己封装了一套严谨的IO操作类,要查看原始网页的内容,也不容易。在毕业设计的过程中,经过一般的摸索,可以由索引得到每个网页的原始内容。因此,后继的文本分类的研究也得以展开。代码如下:
import org.apache.lucene.search.IndexSearcher;
import java.io.*;
import org.apache.lucene.document.Document;
import org.apache.nutch.searcher.FetchedSegments;
import org.apache.nutch.fs.LocalFileSystem;
import java.util.ArrayList;
import java.util.Enumeration;
import org.apache.lucene.document.Field;
import org.apache.nutch.searcher.HitDetails;
/**
* 从索引里面,读取文章内容
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2006</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class ExtractText {
public ExtractText() {
}
public static void main(String[] args) throws IOException {
String path = args[0];//nutch crawl完的主目录 如crawl-20060622203455
File nutchFileRoot = new File(path);
File index = new File(nutchFileRoot,"index");
File segmentsDir = new File(nutchFileRoot,"segments");
File outPut = new File(nutchFileRoot,"plaitext");//存放内容的目录
if(!outPut.isDirectory()){
outPut.mkdir();
}
FetchedSegments segments = new FetchedSegments(new LocalFileSystem(), segmentsDir.toString());
try {
IndexSearcher searcher = new IndexSearcher(index.getAbsolutePath());
for(int i = 0;i<searcher.maxDoc();i++){
Document doc = searcher.doc(i);//依次遍历索引库中的每条记录
String docNo = doc.get("docNo");
String seg = doc.get("segment");
ArrayList fields = new ArrayList();
ArrayList values = new ArrayList();
Enumeration e = doc.fields();
while (e.hasMoreElements()) {
Field field = (Field)e.nextElement();
fields.add(field.name());
values.add(field.stringValue());
}
HitDetails detail = new HitDetails((String[])fields.toArray(new String[fields.size()]),
(String[])values.toArray(new String[values.size()]));
String aa = segments.getParseText(detail).toString();//得到内容
File temp = new File(outPut,seg+"_"+docNo);//输出文件的名字,可以随便起,保证不重复就可以
DataOutputStream outs = new DataOutputStream(new FileOutputStream(temp));
outs.write(aa.getBytes());
outs.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
转自:http://hi.baidu.com/sunky/blog/item/40702ff5c42a9b25bd310949.html