jieba分词太慢,怎么办?找jieba_fast

原文链接:https://www.rtnzero.com/archives/272.html


有时候感觉处理一个几十M的文本,要一分钟才能好,然后调试时各种心焦!

下面举个例子:

归零有一个11.9M的文本文件,是一些抓取到的Python长尾关键词,我们拿它做个实验,看看用jieba分词需要多久:

以下为测试代码:

# -*- coding: utf-8 -*-
# Author : Alven.Gu
import time
import jieba


def timmer (func ):
    def deco (*args , **kwargs ):
        print ( '\n函数:\033[32;1m{_funcname_}()\033[0m 开始运行:'. format (_funcname_ =func.__name__ ) )
        start_time = time. time ( )
        res = func (*args , **kwargs )
        end_time = time. time ( )
        print ( '函数: \033[32;1m{_funcname_}()\033[0m 运行了 {_time_}秒'
              . format (_funcname_ =func.__name__ , _time_ = (end_time - start_time ) ) )
        return res

    return deco


@timmer
def chinese_word_segmentation (txt_file_path , seg_mode = 'search' ):
    with open (txt_file_path , 'r' , encoding = 'utf-8-sig' ) as f:
        all_text_in_file = f. read ( ). replace ( '\r' , '' ). replace ( '\n' , '' ). replace ( '\t' , '' )
    if seg_mode == 'accurate':
        word_generator = jieba. cut (all_text_in_file )
    elif seg_mode == 'full':
        word_generator = jieba. cut (all_text_in_file , cut_all = True )
    else:
        word_generator = jieba. cut_for_search (all_text_in_file )
    return word_generator


@timmer
def generator2dict (word_generator ):
    word_dict = { }
    for word in word_generator:
        if len (word ) < 1:
            continue
        else:
            word_dict [word ] = word_dict. get (word , 0 ) + 1
    return word_dict


def main ( ):
    word_generator = chinese_word_segmentation ( 'python长尾词.txt' )
    word_dict = generator2dict (word_generator )


if __name__ == '__main__':
    main ( )

简述一下流程:
1、程序启动会从main函数开始,先执行分词,分词函数会返回一个生成器。
2、再执行生成器转字典函数
两个函数前都加上了timmer装饰器,所以会打印函数运行所消耗的时间
看下结果:

可以看到分词函数返回生成器所用的时间非常的少,只有消耗了0.17186450958251953秒。
而生成器转字典消耗了26.730547428131104秒。
而这个jieba库慢就慢在这个返回的生成器的效率上。

接下去,我们使用jieba_fast做个对比,对代码做以下修改:
只修改以下语句,其它内容不作修改

# import jieba
import jieba_fast as jieba

我们再来看下测试结果:

可以看到分词函数的运行时间因为本来就很少,所以看不出很明显的变化。
但是生成器转字典的函数运行时间缩短到了15.10241174697876
速度提升了43%

好了看完结果,赶紧去装一个试下吧
安装命令:

pip3 install jieba_fast


看到这个结果是不是还觉得不给劲?没关系,接下去还可以祭出多进程处理,请关注下一篇《Python jieba分词库的多进程处理方法:pool.map()应用实例

—-手—-工—-分—-割—-线—-

文末给大家分享一些本人在学习Python的过程当中,用到的资料(视频、书籍、文档、源码)。

下载链接:https://pan.baidu.com/s/1_qtDzNyeDoAP62A9xxY9ow 提取码:9t62

每一份资料我都精心整理过,留给需要的朋友