lucene第一步---5.中文分词IKAnalyzer和高亮highlighter的使用

 http://llying.iteye.com/blog/570208

 

最近工作比较忙,一直没有更新,还请见谅。
最近lucene已经更新到lucene 3.0版本了 2.X版本的一些用法已经彻底不在支持了。
下面的例子主要是介绍中文分词器IKAnalyzer的使用和Lucene高亮显示。
lucene 3.x版本中有些2.x方法已经完全被剔除了,这里会捎带一下3.x的用法,当然我这里用的还是2.X的版本。
lucene自带的分词方式对中文分词十分的不友好,基本上可以用惨不忍睹来形容,所以这里推荐使用IKAnalyzer进行中文分词。
IKAnalyzer分词器是一个非常优秀的中文分词器。
下面是官方文档上的介绍
采用了特有的“正向迭代最细粒度切分算法“,具有60万字/秒的高速处理能力。
采用了多子处理器分析模式,支持:英文字母(IP地址、Email、URL)、数字(日期,常用中文数量词,罗马数字,科学计数法),中文词汇(姓名、地名处理)等分词处理。
优化的词典存储,更小的内存占用。支持用户词典扩展定义.
针对Lucene全文检索优化的查询分析器
IKQueryParser(作者吐血推荐);采用歧义分析算法优化查询关键字的搜索排列组合,能极大的提高Lucene检索的命中率。
1.IKAnalyzer的部署:将IKAnalyzer3.X.jar部署于项目的lib目录中;IKAnalyzer.cfg.xml与ext_stopword.dic文件放置在代码根目录下即可。
ok 部署完IKAnalyzer我们先来测试一下
Java代码 复制代码  收藏代码
  1. package demo.test;   
  2.   
  3. import java.io.IOException;   
  4. import java.io.StringReader;   
  5.   
  6. import org.apache.lucene.analysis.Analyzer;   
  7. import org.apache.lucene.analysis.TokenStream;   
  8. import org.apache.lucene.analysis.tokenattributes.TermAttribute;   
  9. import org.apache.lucene.analysis.tokenattributes.TypeAttribute;   
  10. import org.wltea.analyzer.lucene.IKAnalyzer;   
  11.   
  12. public class TestIKAnalyzer {   
  13.        
  14.     public static void main(String[] args) throws IOException {   
  15.         Analyzer analyzer = new IKAnalyzer();   
  16.         TokenStream tokenStream = analyzer.tokenStream(""new StringReader("永和服装饰品有限公司"));   
  17.         //2.x写法 3.0之后不支持了   
  18.         /*Token token =new Token();  
  19.         while(tokenStream.next(token)!=null){  
  20.             System.out.println(token.term());  
  21.         }*/  
  22.         //3.x的写法   
  23.         TermAttribute termAtt = (TermAttribute) tokenStream.getAttribute(TermAttribute.class);    
  24.         TypeAttribute typeAtt = (TypeAttribute) tokenStream.getAttribute(TypeAttribute.class);    
  25.   
  26.         while (tokenStream.incrementToken()) {    
  27.             System.out.print(termAtt.term());    
  28.             System.out.print(' ');    
  29.             System.out.println(typeAtt.type());    
  30.         }    
  31.     }   
  32.   
  33. }  
package demo.test;

import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class TestIKAnalyzer {
	
	public static void main(String[] args) throws IOException {
		Analyzer analyzer = new IKAnalyzer();
		TokenStream tokenStream = analyzer.tokenStream("", new StringReader("永和服装饰品有限公司"));
		//2.x写法 3.0之后不支持了
		/*Token token =new Token();
		while(tokenStream.next(token)!=null){
			System.out.println(token.term());
		}*/
		//3.x的写法
		TermAttribute termAtt = (TermAttribute) tokenStream.getAttribute(TermAttribute.class); 
		TypeAttribute typeAtt = (TypeAttribute) tokenStream.getAttribute(TypeAttribute.class); 

		while (tokenStream.incrementToken()) { 
			System.out.print(termAtt.term()); 
			System.out.print(' '); 
			System.out.println(typeAtt.type()); 
		} 
	}

}


分词结果 永和 和服 服装 装饰品 装饰 饰品 有限公司 有限 公司

2.我们开始采用IKAnalyzer创建索引
Java代码 复制代码  收藏代码
  1. package demo.test;   
  2.   
  3. import java.io.BufferedReader;   
  4. import java.io.File;   
  5. import java.io.FileInputStream;   
  6. import java.io.IOException;   
  7. import java.io.InputStreamReader;   
  8.   
  9. import org.apache.lucene.analysis.Analyzer;   
  10. import org.apache.lucene.document.Document;   
  11. import org.apache.lucene.document.Field;   
  12. import org.apache.lucene.index.IndexWriter;   
  13. import org.wltea.analyzer.lucene.IKAnalyzer;   
  14.   
  15. public class CreatIndex {   
  16.   
  17.     @SuppressWarnings("deprecation")   
  18.     public static void main(String[] args) throws IOException {   
  19.         String path = "index";//索引目录   
  20.         Analyzer analyzer = new IKAnalyzer();//采用的分词器   
  21.         IndexWriter iwriter = new IndexWriter(path, analyzer, true);     
  22.         File dir = new File("data");//待索引的数据文件目录   
  23.         File[] files = dir.listFiles();   
  24.         for(int i=0;i<files.length;i++){   
  25.             Document doc = new Document();   
  26.             File file = files[i];   
  27.             FileInputStream fis = new FileInputStream(file);   
  28.             String content = "";   
  29.             BufferedReader reader = new BufferedReader(new InputStreamReader(fis));   
  30.                
  31.             StringBuffer buffer = new StringBuffer("");   
  32.             content = reader.readLine();   
  33.             while (content != null) {   
  34.                 buffer.append(content);   
  35.                 content = reader.readLine();   
  36.             }   
  37.             doc.add(new Field("title",file.getName(),Field.Store.YES,Field.Index.ANALYZED));   
  38.             doc.add(new Field("content",buffer.toString(),Field.Store.YES,Field.Index.ANALYZED));   
  39.             iwriter.addDocument(doc);   
  40.         }   
  41.         iwriter.close();   
  42.     }   
  43.   
  44. }  
package demo.test;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexWriter;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class CreatIndex {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws IOException {
		String path = "index";//索引目录
		Analyzer analyzer = new IKAnalyzer();//采用的分词器
		IndexWriter iwriter = new IndexWriter(path, analyzer, true);  
		File dir = new File("data");//待索引的数据文件目录
		File[] files = dir.listFiles();
		for(int i=0;i<files.length;i++){
			Document doc = new Document();
			File file = files[i];
			FileInputStream fis = new FileInputStream(file);
			String content = "";
			BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
	        
			StringBuffer buffer = new StringBuffer("");
			content = reader.readLine();
			while (content != null) {
			    buffer.append(content);
			    content = reader.readLine();
			}
			doc.add(new Field("title",file.getName(),Field.Store.YES,Field.Index.ANALYZED));
			doc.add(new Field("content",buffer.toString(),Field.Store.YES,Field.Index.ANALYZED));
			iwriter.addDocument(doc);
		}
		iwriter.close();
	}

}

3.对索引进行查询并进行高亮highlighter处理
Java代码 复制代码  收藏代码
  1. package demo.test;   
  2.   
  3. import java.io.File;   
  4. import java.io.IOException;   
  5. import java.io.StringReader;   
  6.   
  7. import org.apache.lucene.analysis.Analyzer;   
  8. import org.apache.lucene.analysis.TokenStream;   
  9. import org.apache.lucene.document.Document;   
  10. import org.apache.lucene.index.Term;   
  11. import org.apache.lucene.search.IndexSearcher;   
  12. import org.apache.lucene.search.Query;   
  13. import org.apache.lucene.search.ScoreDoc;   
  14. import org.apache.lucene.search.TermQuery;   
  15. import org.apache.lucene.search.TopDocs;   
  16. import org.apache.lucene.search.highlight.Highlighter;   
  17. import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;   
  18. import org.apache.lucene.search.highlight.QueryScorer;   
  19. import org.apache.lucene.search.highlight.SimpleFragmenter;   
  20. import org.apache.lucene.search.highlight.SimpleHTMLFormatter;   
  21. import org.apache.lucene.store.Directory;   
  22. import org.apache.lucene.store.FSDirectory;   
  23. import org.wltea.analyzer.lucene.IKAnalyzer;   
  24.   
  25. public class TestHighlighter {   
  26.   
  27.     @SuppressWarnings("deprecation")   
  28.     public static void main(String[] args) throws IOException, InvalidTokenOffsetsException {   
  29.         String path = "index";//索引目录   
  30.         Directory dir = FSDirectory.getDirectory(new File(path));   
  31.         IndexSearcher search = new IndexSearcher(dir);   
  32.         Term term = new Term("content","纯粹");   
  33.         Query query = new TermQuery(term);   
  34.         TopDocs topDocs = search.search(query, 10);   
  35.         ScoreDoc[] hits = topDocs.scoreDocs;   
  36.         //正常产生的查询   
  37.         for(int i=0;i<hits.length;i++){   
  38.             Document doc = search.doc(hits[i].doc);   
  39.             System.out.print(doc.get("title")+":");   
  40.             System.out.println(doc.get("content"));   
  41.         }   
  42.         //高亮设置   
  43.         Analyzer analyzer = new IKAnalyzer();//设定分词器   
  44.         SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<B>","</B>");//设定高亮显示的格式,也就是对高亮显示的词组加上前缀后缀   
  45.         Highlighter highlighter = new Highlighter(simpleHtmlFormatter,new QueryScorer(query));   
  46.         highlighter.setTextFragmenter(new SimpleFragmenter(150));//设置每次返回的字符数.想必大家在使用搜索引擎的时候也没有一并把全部数据展示出来吧,当然这里也是设定只展示部分数据   
  47.         for(int i=0;i<hits.length;i++){   
  48.             Document doc = search.doc(hits[i].doc);   
  49.             TokenStream tokenStream = analyzer.tokenStream("",new StringReader(doc.get("content")));   
  50.             String str = highlighter.getBestFragment(tokenStream, doc.get("content"));   
  51.             System.out.println(str);   
  52.         }   
  53.     }   
  54.   
  55. }  
package demo.test;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.highlight.Highlighter;
import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;
import org.apache.lucene.search.highlight.QueryScorer;
import org.apache.lucene.search.highlight.SimpleFragmenter;
import org.apache.lucene.search.highlight.SimpleHTMLFormatter;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class TestHighlighter {

	@SuppressWarnings("deprecation")
	public static void main(String[] args) throws IOException, InvalidTokenOffsetsException {
		String path = "index";//索引目录
		Directory dir = FSDirectory.getDirectory(new File(path));
		IndexSearcher search = new IndexSearcher(dir);
		Term term = new Term("content","纯粹");
		Query query = new TermQuery(term);
		TopDocs topDocs = search.search(query, 10);
		ScoreDoc[] hits = topDocs.scoreDocs;
		//正常产生的查询
		for(int i=0;i<hits.length;i++){
			Document doc = search.doc(hits[i].doc);
			System.out.print(doc.get("title")+":");
			System.out.println(doc.get("content"));
		}
		//高亮设置
		Analyzer analyzer = new IKAnalyzer();//设定分词器
		SimpleHTMLFormatter simpleHtmlFormatter = new SimpleHTMLFormatter("<B>","</B>");//设定高亮显示的格式,也就是对高亮显示的词组加上前缀后缀
		Highlighter highlighter = new Highlighter(simpleHtmlFormatter,new QueryScorer(query));
		highlighter.setTextFragmenter(new SimpleFragmenter(150));//设置每次返回的字符数.想必大家在使用搜索引擎的时候也没有一并把全部数据展示出来吧,当然这里也是设定只展示部分数据
		for(int i=0;i<hits.length;i++){
			Document doc = search.doc(hits[i].doc);
			TokenStream tokenStream = analyzer.tokenStream("",new StringReader(doc.get("content")));
			String str = highlighter.getBestFragment(tokenStream, doc.get("content"));
			System.out.println(str);
		}
	}

}


大家可以看到对于关键词的数据已经进行高亮处理了。 “中后期,不少群组改名<B>纯粹</B>是赶潮流和恶搞。”

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值