基于IKAnalyzer搭建分词服务

背景

前端高亮需要分词服务,nlp团队提供的分词服务需要跨域调用,而且后台数据索引使用的IK分词。综合评价,前端分词也需要基于IK分词器。
IKAnalyzer服务已经停止更新,且对Lucene支持仅测试到4.x.x版本(6.x.x会出现异常),因此使用IK分词器时需要解决一些异常。

依赖

项目以及maven构建,需要指定IK依赖以及Lucene依赖如下:

<dependency>
   <groupId>com.janeluo</groupId>
   <artifactId>ikanalyzer</artifactId>
   <version>2012_u6</version>
</dependency>
<dependency>
   <groupId>org.apache.lucene</groupId>
   <artifactId>lucene-core</artifactId>
   <version>4.10.4</version>
</dependency>

代码

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.IOException;
import java.io.StringReader;

/**
 * Created by liutingna on 2018/5/31.
 *
 * @author liutingna
 */
public class IKAnalyzerTest {
    public static void main(String[] args) throws Exception {
        String text = "lxw的大数据田地 -- lxw1234.com 专注Hadoop、Spark、Hive等大数据技术博客。 北京优衣库";
        Analyzer analyzer = new IKAnalyzer(false);
        StringReader reader = new StringReader(text);
        try {
            TokenStream tokenStream = analyzer.tokenStream("", reader);
            tokenStream.reset();
            while (tokenStream.incrementToken()) {
                CharTermAttribute termAttribute = tokenStream.getAttribute(CharTermAttribute.class);
                System.out.println(termAttribute.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        analyzer.close();
        reader.close();
    }
}

配置文件

在项目根目录下,加入IK配置文件IKAnalyzer.cfg.xml,其中指定用户字典和停用词字典。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
    <comment>IK Analyzer 扩展配置</comment>
    <!--用户可以在这里配置自己的扩展字典 -->
    <entry key="ext_dict">main.dic</entry>
    <!--用户可以在这里配置自己的扩展停止词字典-->
    <entry key="ext_stopwords">hit_stopwords.dic</entry>
    <!--用户可以在这里配置远程扩展字典 -->
    <!-- <entry key="remote_ext_dict">words_location</entry> -->
    <!--用户可以在这里配置远程扩展停止词字典-->
    <!-- <entry key="remote_ext_stopwords">words_location</entry> -->
</properties>

配置用户字典

添加main.dic文件,根据上述IK配置文件,该用户字典放在同级目录下。每个词占一行,使用UTF-8编码,并以dic格式保存。

配置停用词

添加hit_stopwords.dic文件,根据上述IK配置文件,该用户字典放在同级目录下。每个词占一行,使用UTF-8编码,并以dic格式保存。

注意

因为lucene-core依赖版本较低,因此需要与项目中其他对lucene有依赖的组件进行验证。
因为项目中使用的Elasticsearch对lucene依赖版本为6.x,造成与IK依赖的lucene(4.x)冲突,最终放弃使用了ik,而是用结巴分词代替。

常见问题

Exception in thread "main" java.lang.AbstractMethodError: org.apache.lucene.analysis.Analyzer.createComponents(Ljava/lang/String;)Lorg/apache/lucene/analysis/Analyzer$TokenStreamComponents;
    at org.apache.lucene.analysis.Analyzer.tokenStream(Analyzer.java:162)
    at com.inspur.analysis.kg.util.IKAnalyzerTest.main(IKAnalyzerTest.java:22)

【解决】:版本不匹配,可以换lucene-core版本,比如4.10.4

猜你喜欢

转载自www.cnblogs.com/yanl55555/p/12540732.html