对于lucene自带分词器,没有一个能很好的处理中文的分词,因此,我们使用的分词的时候,往往会使用国人开发的一个分词器IKAnalyzer,使用非常简单,只需要将jar包拷入即可。
如果需要扩展词库或者停用词,只需要在src下放入扩展的词库(*.dic文件),并在配置文件中引用即可,注意,新增的词库必须满足的要求是:一个词语占一行。packagelucene;
importjava.io.IOException;
importjava.io.StringReader;
importorg.apache.lucene.analysis.Analyzer;
importorg.apache.lucene.analysis.TokenStream;
importorg.apache.lucene.analysis.standard.StandardAnalyzer;
importorg.apache.lucene.analysis.tokenattributes.CharTermAttribute;
importorg.junit.Test;
publicclassTokenTest{
@Test
publicvoidtest()throwsIOException{
Analyzeranalyzer=newStandardAnalyzer();
Stringtext="我爱北京天安门";
TokenStreamtokenStream=analyzer.tokenStream("",text);
tokenStream.reset();
while(tokenStream.incrementToken()){
CharTermAttributecharTermAttribute=tokenStream.addAttribute(CharTermAttribute.class);
System.out.println(charTermAttribute);
}
}
@Test
publicvoidtestChineseAnalyzer()throwsException{
//中文分词
Stringtext="传智播客:Lucene是全文检索的框架";
/*//单字分词StandardAnalyzer、ChineseAnalyzer
Analyzeranalyzer=newStandardAnalyzer(Version.LUCENE_30);//也是单字分词
Analyzeranalyzer2=newChineseAnalyzer();//也是单字分词
//相连的两个字组合在一起
Analyzeranalyzer3=newCJKAnalyzer(Version.LUCENE_30);*/
//词库分词IKAnalyzer
Analyzeranalyzer=newIKAnalyzer();
testAnalyzer(analyzer,text);
}
/**
*使用指定的分词器对指定的文本进行分词,并打印结果--不需要掌握
*@paramanalyzer
*@paramtext
*@throwsException
*/
publicvoidtestAnalyzer(Analyzeranalyzer,Stringtext)throwsException{
System.out.println("当前使用的分词器:"+analyzer.getClass());
TokenStreamtokenStream=analyzer.tokenStream("content",newStringReader(text));
tokenStream.addAttribute(CharTermAttribute.class);
while(tokenStream.incrementToken()){
CharTermAttributetermAttribute=tokenStream.getAttribute(CharTermAttribute.class);
System.out.println(termAttribute);
}
}
}