Lucene使用(四)中文分词器smartcn

本文介绍了如何在Lucene中使用SmartChineseAnalyzer进行中文分词,并探讨了自定义停用词的方法,以优化搜索效果。
摘要由CSDN通过智能技术生成
Lucene自带多种分词器,其中对中文分词支持比较好的是smartcn。

1. 标准分词器StandardAnalyzer

在演示smartcn中文分词器之前,先来看看Lucene标准分词器对中文分词的效果。需要的jar为\lucene-5.5.5\core\下的lucene-core-5.5.5.jar和\lucene-5.5.5\analysis\common\下的lucene-analyzers-common-5.5.5.jar。新建测试类TestLucene04:
package net.xxpsw.demo.lucene.test;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
public class TestLucene04 {
	private void print(Analyzer analyzer) throws Exception {
		String text = "Lucene自带多种分词器,其中对中文分词支持比较好的是smartcn。";
		TokenStream tokenStream = analyzer.tokenStream("content", text);
		CharTermAttribute attribute = tokenStream.addAttribute(CharTermAttribute.class);
		tokenStream.reset();
		while (tokenStream.incr
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Lucene使用中文分词ik-analyzers可以自定义字典。下面是一个简单的例子: 1. 首先,下载ik-analyzers的jar包,将其添加到项目的classpath中。 2. 创建一个自定义词典文件,例如mydict.txt,将需要添加的词语逐行写入该文件。 3. 在代码中使用以下代码片段来加载自定义词典: ```java // 创建IK分词 Analyzer analyzer = new IKAnalyzer(true); // 获取IK分词的配置对象 IKAnalyzerConfig config = ((IKAnalyzer) analyzer).getConfig(); // 加载自定义词典 config.setUseSmart(true); config.setMainDictionary("mydict.dic"); config.setQuantifierDicionary("mydict.qdic"); ``` 其中,IKAnalyzerConfig是IK分词的配置对象,通过该对象可以设置分词的一些参数。setMainDictionary和setQuantifierDicionary方法分别用于设置主词典和量词词典的文件名。 4. 使用分词进行分词: ```java // 创建分词 Analyzer analyzer = new IKAnalyzer(true); // 对字符串进行分词 String text = "我爱北京天安门"; TokenStream tokenStream = analyzer.tokenStream("", new StringReader(text)); // 遍历分词结果 CharTermAttribute charTermAttribute = tokenStream.addAttribute(CharTermAttribute.class); tokenStream.reset(); while (tokenStream.incrementToken()) { System.out.println(charTermAttribute.toString()); } tokenStream.end(); tokenStream.close(); ``` 在以上代码中,我们创建了一个IK分词并对一个字符串进行了分词,遍历分词结果并输出。 注意:在使用自定义词典时,需要保证自定义词典的文件名与代码中设置的文件名一致,并且自定义词典文件必须放在分词的类路径下。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xxpsw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值