lucene入门代码四(使用css高亮文本)

1.本代码需要的jar包有:
[color=green]lucene-core-3.0.0.jar
lucene-analyzers-3.0.0.jar
lucene-highlighter-3.0.0.jar[/color]
代码如下:

package com.yale.lucene;

import java.io.FileWriter;
import java.io.StringReader;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.search.highlight.SimpleSpanFragmenter;
import org.apache.lucene.util.Version;

/**
*
* 使用CSS高亮terms
*
*/
public class HighlightTermsUseCSS
{
private static final String text =
"In this section we'll show you how to make the simplest " +
"programmatic query, searching for a single term, and then " +
"we'll see how to use QueryParser to accept textual queries. " +
"In the sections that follow, we’ll take this simple example " +
"further by detailing all the query types built into Lucene. " +
"We begin with the simplest search of all: searching for all " +
"documents that contain a single term.";
public static void main(String[] args) throws Exception
{
//将高亮后的html代码写入此文件
String filename="F://新建文件夹//luceneTest//dataSource//highlight.html";
//要搜索的关键字
String searchText = "term";
//创建QueryParser
QueryParser parser = new QueryParser(Version.LUCENE_30,"f",new StandardAnalyzer(Version.LUCENE_30));
//得到Query
Query query = parser.parse(searchText);
//要高亮的文本添加样式
SimpleHTMLFormatter formatter = new SimpleHTMLFormatter("<span class=\"highlight\">","</span>");
//TokenStream用来分析文字流,按一定的规则罗列token
TokenStream tokens = new StandardAnalyzer(Version.LUCENE_30).tokenStream("f",new StringReader(text));
//声明查询记分器
QueryScorer scorer = new QueryScorer(query,"f");
//声明高亮的关键类
Highlighter highlighter = new Highlighter(formatter,scorer);
//设置段划分器;使用SimpleSpanFragmenter
highlighter.setTextFragmenter(new SimpleSpanFragmenter(scorer));
//得到高亮的片段
String result = highlighter.getBestFragments(tokens,text,3,"...");
//写入文件操作
FileWriter writer = new FileWriter(filename);
writer.write("<html>");
writer.write("<style>\n" +
".highlight {\n" +
" background: yellow;\n" +
"}\n" +
"</style>");
writer.write("<body>");
writer.write(result);
writer.write("</body></html>");
writer.close();
System.out.println("完成");

}
}

[size=large][color=red]效果图如下:[/color][/size]


[img]http://dl.iteye.com/upload/attachment/0069/0389/c5a46954-e8cd-3226-b5cd-e77c22573a9e.png[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值