jieba 自定义词库(海量词语)以及模型复用

简介

网络上有很多介绍 jieba 自定义词库的文章。
但基本都是浅显的模仿官方文档,告诉读者使用 jieba.add_word 或者  jieba.load_userdict。

但在实际生产中,需要面对:
1 自定义词典可能会非常大 
2 每次重启程序都需要较长时间 
3 不知道如何复用词典模型

本文将解决上述问题。

为啥要自建词库

使用默认词库,往往会把特定词语进行分词,而我们希望这些词语完整的出现,不被拆分。
使用自定义词典,将这种词语放到词库模型中,即可避免这种问题。

自建词库的两种方式

jieba.add_word 或者 jieba.load_userdict(使用方法自己查,这里暂且不表。)

坑坑

没错,就是 jieba.load_userdict。

使用这个方法,每次程序重启的时候,都要重新加载,非常耗时。本人测试 400 万条词语时,加载需要 5 分钟左右。

这个加载非常耗时的原因是:该加载自定义词库的过程,是一个单线程的 IO 过程。看源码

def load_userdict(self, f):
    '''
    Load personalized dict to improve detect rate.

    Parameter:
        - f : A plain text file contains words and their ocurrences.
              Can be a file-like object, or the path of the dictionary file,
              whose encoding must be utf-8.

    Structure of dict file:
    word1 freq1 word_type1
    word2 freq2 word_type2
    ...
    Word type may be ignored
    '''
    self.check_initialized()
    if isinstance(f, string_types):
        f_name = f
        f = open(f, 'rb')
    else:
        f_name = resolve_filename(f)
    for lineno, ln in enumerate(f, 1):
        line = ln.strip(
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值