之前想做lucene的中文分词,上网一搜,结果都是针对lucene2.x的,于是就写了一实例针对lucene3.x版本的,以下仅为学习交流之用;
时间仓促,实例示下:
输出结果如下:
时间仓促,实例示下:
package com.hpjianhua.lucene;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.TermAttribute;
import org.apache.lucene.util.Version;
import org.wltea.analyzer.lucene.IKAnalyzer;
/**
* 分词器测试类,支持lucene3.0以上版本
* 分词器IKAnalyzer3.2.5Stable.jar
* @author hpjianhua
* @Date 2011 04 08
*
*/
public class TokenTest {
// 要分词的字符串
private static String text = "中国,古时通常泛指中原地区,与中华中夏 中土中州含义相同。古代华夏族、汉族建国于黄河流域一带,以为居天下之中,故称中国";
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Analyzer ikAnalyzer = new IKAnalyzer();
System.out.println("======中文=======IKAnalyzer======分词=======");
showToken(ikAnalyzer, text);
Analyzer standardAnalyzer = new StandardAnalyzer(Version.LUCENE_30);
System.out.println("=====一元========StandardAnalyzer=====分词========");
showToken(standardAnalyzer, text);
}
/**
* 分词及打印分词结果的方法
* @param analyzer 分词器名称
* @param text 要分词的字符串
* @throws IOException 抛出的异常
*/
public static void showToken(Analyzer analyzer, String text) throws IOException {
Reader reader = new StringReader(text);
TokenStream stream = (TokenStream)analyzer.tokenStream("", reader);
//添加工具类 注意:以下这些与之前lucene2.x版本不同的地方
TermAttribute termAtt = (TermAttribute)stream.addAttribute(TermAttribute.class);
OffsetAttribute offAtt = (OffsetAttribute)stream.addAttribute(OffsetAttribute.class);
// 循环打印出分词的结果,及分词出现的位置
while(stream.incrementToken()){
System.out.print(termAtt.term() + "|("+ offAtt.startOffset() + " " + offAtt.endOffset()+")");
}
System.out.println();
}
}
输出结果如下:
======中文=======IKAnalyzer======分词=======
中国|(0 2)古时|(3 5)通常|(5 7)泛指|(7 9)中原地区|(9 13)中原|(9 11)原地区|(10 13)原地|(10 12)地区|(11 13)与|(14 15)中华|(15 17)华中|(16 18)中夏|(17 19)中土|(20 22)中州|(22 24)含义|(24 26)相同|(26 28)古代|(29 31)华夏|(31 33)夏|(32 33)族|(33 34)汉族|(35 37)建国|(37 39)于|(39 40)黄河流域|(40 44)黄河|(40 42)河流|(41 43)流域|(42 44)一带|(44 46)一|(44 45)以为|(47 49)居|(49 50)天下|(50 52)之中|(52 54)故|(55 56)称|(56 57)中国|(57 59)
=====一元========StandardAnalyzer=====分词========
中|(0 1)国|(1 2)古|(3 4)时|(4 5)通|(5 6)常|(6 7)泛|(7 8)指|(8 9)中|(9 10)原|(10 11)地|(11 12)区|(12 13)与|(14 15)中|(15 16)华|(16 17)中|(17 18)夏|(18 19)中|(20 21)土|(21 22)中|(22 23)州|(23 24)含|(24 25)义|(25 26)相|(26 27)同|(27 28)古|(29 30)代|(30 31)华|(31 32)夏|(32 33)族|(33 34)汉|(35 36)族|(36 37)建|(37 38)国|(38 39)于|(39 40)黄|(40 41)河|(41 42)流|(42 43)域|(43 44)一|(44 45)带|(45 46)以|(47 48)为|(48 49)居|(49 50)天|(50 51)下|(51 52)之|(52 53)中|(53 54)故|(55 56)称|(56 57)中|(57 58)国|(58 59)