1. 官方文档及参考连接java
2. 源码解析算法
分析 com.hankcs.demo包下的DemoCustomDictionary.java 基于自定义词典使用标准分词HanLP.segment(text)的大体流程(HanLP版本1.5.3)。首先把自定义词添加到词库中:spa
CustomDictionary.add("攻城狮");orm
CustomDictionary.insert("白富美", "nz 1024");//指定了自定义词的词性和词频对象
CustomDictionary.add("单身狗", "nz 1024 n 1")//一个词能够有多个词性blog
添加词库的过程包括:文档
public static boolean add(String word)get
{源码
if (HanLP.Config.Normalization) word = CharTable.convert(word);博客
if (contains(word)) return false;//判断DoubleArrayTrie和BinTrie是否已经存在word
return insert(word, null);
}
public static boolean insert(String word, String natureWithFrequency)
{
if (word == null) return false;
if (HanLP.Config.Normalization) word = CharTable.convert(word);
CoreDictionary.Attribute att = natureWithFrequency == null ? new CoreDictionary.Attribute(Nature.nz, 1) : CoreDictionary.Attribute.create(natureWithFrequency);
if (att == null) return false;
if (dat.set(word, att)) return true;
//"攻城狮"是动态加入的词语. 在核心词典中未匹配到,在自定义词典中也未匹配到, 动态增删的词语使用BinTrie保存
if (trie == null) trie = new BinTrie<CoreDictionary.Attribute>();
trie.put(word, att);
return true;
}
将自定义添加到BinTrie树后,接下来是使用分词算法分词了。假设使用的标准分词(viterbi算法来分词):
List<Vertex> vertexList = viterbi(wordNetAll);
分词具体过程可参考:
分词完成以后,返回的是一个 Vertex 列表。以下图所示:
而后根据 是否开启用户自定义词典 配置来决定将分词结果与用户添加的自定义词进行合并。默认状况下,config.useCustomDictionary是true,即开启用户自定义词典。
if (config.useCustomDictionary)
{
if (config.indexMode > 0)
combineByCustomDictionary(vertexList, wordNetAll);
else combineByCustomDictionary(vertexList);
}
combineByCustomDictionary(vertexList)由两个过程组成:
//DAT合并
DoubleArrayTrie<CoreDictionary.Attribute> dat = CustomDictionary.dat;
....
// BinTrie合并
if (CustomDictionary.trie != null)//用户经过CustomDictionary.add("攻城狮"); 动态增长了词典
{
....
合并以后的结果以下:
3. 关于用户自定义词典
总结一下,开启自定义分词的流程基本以下:
HanLP做者在HanLP issue783:上面说:词典不等于分词、分词不等于天然语言处理;推荐使用语料而不是词典去修正统计模型。因为分词算法不能将一些“特定领域”的句子分词正确,因而为了纠正分词结果,把想要的分词结果添加到自定义词库中,但最好使用语料来纠正分词的结果。另外,做者还说了在之后版本中不保证继续支持动态添加自定义词典。以上是阅读源码过程当中的一些粗浅理解,仅供参考。
文章转载自hapjin 的博客