有时候需要使用自定义的词库,不使用默认的词库。比如做敏感词分词时, 完全禁用掉默认词库。
jieba 分词里面可以这样处理,通过set_dictionary 来设置自定义词库,从而禁用掉默认词库。
import jieba
jieba.set_dictionary("words.txt")
jieba.initialize()
seg_list = jieba.cut("helloworldfromshanghai你好世界")
print(", ".join(seg_list))
words.txt 的内容
hello 1
world 1
分词出来的内容是这样的:
hello, world, fromshanghai, 你, 好, 世界
世界还是被分成一个词语了。 这个原因并不是词库没有生效,而是因为默认启用了 HMM的新词识别。
世界被识别成了一个词语。禁用 HMM 即可:
import jieba
jieba.set_dictionary("words.txt")
seg_list = jieba.cut("helloworldfromhangzhou你好世界", HMM=False)
print(", ".join(seg_list))