发布于 2015-04-24 12:57:32 | 279 次阅读 | 评论: 0 | 来源: 网友投递

这里有新鲜出炉的Lucene教程,程序狗速度看过来!

Apache Lucene全文检索引擎工具包

Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础建立起完整的全文检索引擎。


这段代码的功能是利用PDFBox.zip的包
利用lucene对PDF文本进行内容的解析
读取pdf文件的内容。然后重新的写入到同名的.txt文件中

结果截图:

示例代码

package pdfbox;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.MalformedURLException;
import java.net.URL;


import org.pdfbox.pdmodel.PDDocument;
import org.pdfbox.util.PDFTextStripper;


public class PdfBox {


public PdfBox() {
// TODO Auto-generated constructor stub

}
public void geText(String file) throws Exception{
//是否排序
boolean sort = false;

//pdf名称
String pdfFile = file;

//输入文本文件名称
String textFile = null;


//设置编码方式
String encoding = "UTF-8";

//开始提取页数
int startPage = 1;

//结束提取页数
int endPage = Integer.MAX_VALUE;

//文件输入流,生成文本文件
Writer output = null;

//内存中存储的PDF Document
PDDocument document = null;

try{
try{
//首先当做一个URL来装载文件,
//如果得到异常再从本地文件系统去装载文件
URL url = new URL(pdfFile);
document = PDDocument.load(url);

//获取PDF的文件名
String fileName = url.getFile();

//原来的PDF名称来命名新产生的txt文件
if(fileName.length( ) > 4){
File outputFile = new File(fileName.substring(0, fileName.length() - 4) + ".txt");
textFile = outputFile.getName();
}
}catch(MalformedURLException r){

//如果作为URl装载到异常则从文件系统装载
document = PDDocument.load(pdfFile);
if(pdfFile.length() > 4){
textFile = pdfFile.substring(0, pdfFile.length() - 4) + ".txt";
}

}
//文件输入流,写入文件到textFile
output = new OutputStreamWriter(new FileOutputStream(textFile), encoding);

//PDFTextStripprt来提取文件
PDFTextStripper stripper = null;
stripper = new PDFTextStripper();

//设置是否排序
stripper.setSortByPosition(sort);

//设置起始页
stripper.setStartPage(startPage);

//设置结束页
stripper.setEndPage(endPage);

//调用PDFTextStripper的writerText提取并输出
stripper.writeText(document, output);

}finally{
//关闭输出流
if(output != null)
output.close();
}
//关闭PDF Document
if(document != null){
document.close();
}
} 

public static void main(String[] args) {
// TODO Auto-generated method stub
PdfBox test = new PdfBox();
try{
//获取E:Lucene项目下的C语言代码.pdf的内容
test.geText("E:\Lucene项目\C语言代码.pdf");

}catch(Exception e){
e.printStackTrace();
}
}
}


最新网友评论  共有(0)条评论 发布评论 返回顶部

Copyright © 2007-2017 PHPERZ.COM All Rights Reserved   冀ICP备14009818号  版权声明  广告服务