IKAnalyzer 3.2经过List方式加入自定义词典

IKAnalyzer 3.2通过List方式加入自定义词典

首先我们查看IKAnalyzer的源码,看词典存储位置:

class DictSegment implements Comparable<DictSegment>{
	
	//公用字典表,存储汉字
	private static final Map<Character , Character> charMap = new HashMap<Character , Character>(16 , 0.95f);
	//数组大小上限
	private static final int ARRAY_LENGTH_LIMIT = 3;
..................
}

 我们可以看到org.wltea.analyzer.dic.DictSegment.charMap是用来公用字典表,存储汉字,那么我们可以在加载词典的时候清空之。

在加入词典的时候可以通过配置文件的方式,但是一般不很现实,有时候需要用户维护动态的字典,那么字典就应该以List的形式加入,我们发现Dictionary.loadExtendWords(List extWords)可以以List的形式加入,代码如下:

	Dictionary.loadExtendWords(Utils.getDicList());

 综上整体代码如下:

Class ownerClass = Class.forName("org.wltea.analyzer.dic.DictSegment");
Field fs = ownerClass.getDeclaredField("charMap");
fs.setAccessible(true);
Map map = (Map) fs.get(ownerClass);
map.clear();
Dictionary.loadExtendWords(Utils.getDicList());
 PS:上述代码仅适用IKAnalyzer 3.2.*,发现2012的代码已经修改成单利了,同时接口变动比较大,采用100w的文章对之切词发现速度没有声明的那么快。