java lucene 分词器_中文分词器—IKAnalyzer

对于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);

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值