3.1 中文分词器—IKAnalyzer

2016-02-17 00:24:35 5,932 0


对于lucene自带分词器,没有一个能很好的处理中文的分词,因此,我们使用的分词的时候,往往会使用国人开发的一个分词器IKAnalyzer,使用非常简单,只需要将jar包拷入即可。

如果需要扩展词库或者停用词,只需要在src下放入扩展的词库(*.dic文件),并在配置文件中引用即可,注意,新增的词库必须满足的要求是:一个词语占一行。

package lucene;

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.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.junit.Test;

public class TokenTest {
    @Test
    public void test() throws IOException{
        Analyzer analyzer=new StandardAnalyzer();
        String text = "我爱北京天安门";
        TokenStream tokenStream = analyzer.tokenStream("", text);
        tokenStream.reset();
        while (tokenStream.incrementToken()) {
            CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class);
            System.out.println(charTermAttribute);
            
        }
    }
    
    @Test
    public void testChineseAnalyzer() throws Exception{
        //中文分词
        String text="传智播客:Lucene是全文检索的框架";
        
/*        //单字分词StandardAnalyzer、ChineseAnalyzer
        Analyzer analyzer=new StandardAnalyzer(Version.LUCENE_30);//也是单字分词
        Analyzer analyzer2=new ChineseAnalyzer();//也是单字分词
        
        //相连的两个字组合在一起
        Analyzer analyzer3=new CJKAnalyzer(Version.LUCENE_30);*/
        
        //词库分词IKAnalyzer
        Analyzer analyzer=new IKAnalyzer();
        
        testAnalyzer(analyzer, text);
    }
    
    /**
     * 使用指定的分词器对指定的文本进行分词,并打印结果--不需要掌握
     * @param analyzer
     * @param text
     * @throws Exception
     */
public void testAnalyzer(Analyzer analyzer, String text) throws Exception {
    System.out.println("当前使用的分词器:" + analyzer.getClass());

    TokenStream tokenStream = analyzer.tokenStream("content", new StringReader(text));
    tokenStream.addAttribute(CharTermAttribute.class);

    while (tokenStream.incrementToken()) {
        CharTermAttribute termAttribute = tokenStream.getAttribute(CharTermAttribute.class);
        System.out.println(termAttribute);
    }
}

}