如何使jieba自定义词典持久化

2019-11-11  本文已影响0人  菜菜鑫

jieba分词是利用python进行自然语言处理中必不可少的常用工具,添加自定义词典也是jieba分词中的的常用功能。

然而每次运行程序,jieba自定义词典都需要重新加载,添加的自定义词典只对当前程序生效。如果自定义词典的数量比较巨大(百万级及以上),每次重新加载这一步将会耗费很长的时间。

网上找不到相关的持久化解决方案,只会告诉你如何使用jieba.load_userdict,所以我的这个完整的持久化方案也算是全网首发了。

事先准备好自定义词典:

创建一个txt文件,然后写入你的分词,一个词占一行;每一行分三部分:词语、词频(可省略)、词性(可省略),用空格隔开,顺序不可颠倒。类似于如下形式:

沈孟良 360 nr
富民理财睿盈 360 nfp
广发多添富 360 nfp

方案分析:

Building prefix dict from the default dictionary ...
Loading model from cache /tmp/jieba.cache
Loading model cost 0.474 seconds.
Prefix dict has been built succesfully.
git clone https://github.com/fxsjy/jieba.git

为了防止和系统中已安装的jieba重名,可以把这个文件重命名为jieba_local

 load_from_cache_fail = True
            if os.path.isfile(cache_file) and (abs_path == DEFAULT_DICT or
                os.path.getmtime(cache_file) > os.path.getmtime(abs_path)):
                default_logger.debug(
                    "Loading model from cache %s" % cache_file)
                try:
                    with open(cache_file, 'rb') as cf:
                        self.FREQ, self.total = marshal.load(cf)
                    load_from_cache_fail = False
                except Exception:
                    load_from_cache_fail = True

            if load_from_cache_fail:
                wlock = DICT_WRITING.get(abs_path, threading.RLock())
                DICT_WRITING[abs_path] = wlock
                with wlock:
                    self.FREQ, self.total = self.gen_pfdict(self.get_dict_file())
                    default_logger.debug(
                        "Dumping model to file cache %s" % cache_file)
                    try:
                        # prevent moving across different filesystems
                        fd, fpath = tempfile.mkstemp(dir=tmpdir)
                        with os.fdopen(fd, 'wb') as temp_cache_file:
                            marshal.dump(
                                (self.FREQ, self.total), temp_cache_file)
                        _replace_file(fpath, cache_file)
                    except Exception:
                        default_logger.exception("Dump cache file failed.")

                try:
                    del DICT_WRITING[abs_path]
                except KeyError:
                    pass

所以要把我们的自定义词典添加到dict.txt中,并且让之后的每次都成功调用缓存文件,就不会再次加载词典了。Nice!

更改分词器(默认为 jieba.dt)的 tmp_dir 和 cache_file 属性,可分别指定缓存文件所在的文件夹及其文件名,用于受限的文件系统。

这样我们就可以指定jieba缓存的文件夹的文件名了。

方案实施

分析了修改的思路和原理,下面开始实施方案:

import jieba_local

jieba_local.dt.tmp_dir = './'
jieba_local.dt.cache_file = 'jieba.temp'
for i in jieba_local.cut('恭喜FPX夺冠啦啦啦啦'):
    print(i)
jieba_local.dt.tmp_dir = './'
jieba_local.dt.cache_file = 'jieba.temp'
Building prefix dict from the default dictionary ...
Loading model from cache ./jieba.temp
Loading model cost 28.665 seconds.
Prefix dict has been built succesfully.

\color{red}{(涉及公司机密,完整代码和数据无法提供,请见谅,纯原创,转载请注明来源)}

上一篇下一篇

猜你喜欢

热点阅读