哈工大分词器中自定义词典的使用

首先在/usr/local/ltp下放置一个词典,我为了测试就叫userdict.txt ,里面有三个词:
解空间
深度优先
根节点

先测试加入自定义词典时的效果:

py@ubuntu:/usr/local/ltp$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> from pyltp import Segmentor
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf-8')
>>> model_path = "/usr/local/ltp/cws.model"
>>> user_dict = "/usr/local/ltp/userdict.txt"
>>> segmentor = Segmentor()
>>> segmentor.load_with_lexicon(model_path, user_dict)
[INFO] 2017-09-04 23:23:24 loaded 3 lexicon entries
>>> sent = "在包含问题的所有解的解空间树中,按照深度优先搜索的策略,从根节点出发深度探索 解空间树。"
>>> words = segmentor.segment(sent)
>>> print ' '.join(words)
在    包含    问题    的    所有    解    的    解空间    树    中    ,    按照    深度优先    搜索    的    策略    ,    从    根节点    出发    深度    探索    解空间    树    。


没加自定义词典时的效果:
py@ubuntu:/usr/local/ltp$ python
Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import os
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.setdefaultencoding('utf-8')
>>> model_path = "/usr/local/ltp/cws.model"
>>> segmentor = Segmentor()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'Segmentor' is not defined
>>> from pyltp import Segmentor
>>> segmentor = Segmentor()
>>> segmentor.load(model_path)
>>> words = segmentor.segment("在包含问题的所有解的解空间树中,按照深度优先搜索的策略,从根节点出发深度探索 解空间树。")
>>> print ' '.join(words)
在    包含    问题    的    所有    解    的    解    空间    树    中    ,    按照    深度    优先    搜索    的    策略    ,    从    根节点    出发    深度    探索    解    空间    树    。


从结果看加与不加自定义词典是显而易见的。

原文地址:https://www.cnblogs.com/herosoft/p/8134223.html