IKAnalyzer

我们的项目中中文切词使用的是mmseg,有一个不满意的地方是jar包中的默认词典一定会被加载进去,当我对有些term有意见时,无法删除。

mmseg中Dictionary.java里一段代码保证了/data/words.dic的加载,我无法提供自己的进行替换。

//try load words.dic in jar
InputStream wordsDicIn = this.getClass().getResourceAsStream("/data/words.dic");
if(wordsDicIn != null) {
    File wordsDic = new File(this.getClass().getResource("/data/words.dic").getFile());
    loadWord(wordsDicIn, dic, wordsDic);
}

而IKAnalyzer就比较自由,既可以增加自己的词典,也能指定删除默认词典中的词。

        String text = "给我讲一个黄色笑话";
        Configuration cfg = DefaultConfig.getInstance();
        Dictionary.initial(cfg);
        //将"黄色笑话"从默认词典中删除
        Dictionary.getSingleton().disableWords(Arrays.asList("黄色笑话"));

        StringReader sr = new StringReader(text);

        IKSegmenter ik = new IKSegmenter(sr, true);
        Lexeme lex;
        while ((lex = ik.next()) != null) {
            System.out.print(lex.getLexemeText() + "|");
        }

输出:给我讲一个|黄色|笑话

如何增加新词呢?

DefaultConfig类会默认加载根目录下的配置文件IKAnalyzer.cfg.xml

<properties>

    <comment>IK Analyzer 扩展配置</comment>
    <!-- 用户可以在这里配置自己的扩展字典 -->
    <entry key="ext_dict">ik.add.dic</entry>
    <!-- 用户可以在这里配置自己的扩展停止词字典    -->
    <!--entry key="ext_stopwords">/dicdata/ext_stopword.dic</entry-->

</properties>

其中ext_dict就是用于添加自定义的扩展词典。  

  

posted @ 2016-12-09 15:21  春文秋武  阅读(722)  评论(0编辑  收藏  举报