jieba库:Tokenizer()类详解:(五)tokenize分词

2021SC@SDUSC


官方的文档里测试已经很明确了,就不在这里赘述了,分析一下源码好了~


源码:

 def tokenize(self, unicode_sentence, mode="default", HMM=True):
        """
        Tokenize a sentence and yields tuples of (word, start, end)

        Parameter:
            - sentence: the str(unicode) to be segmented.
            - mode: "default" or "search", "search" is for finer segmentation.
            - HMM: whether to use the Hidden Markov Model.
        """
        if not isinstance(unicode_sentence, text_type):
            raise ValueError("jieba: the input parameter should be unicode.")
        start = 0
        if mode == 'default':
            for w in self.cut(unicode_sentence, HMM=HMM):
                width = len(w)
                yield (w, start, start + width)
                start += width
        else:
            for w in self.cut(unicode_sentence, HMM=HMM):
                width = len(w)
                if len(w) > 2:
                    for i in xrange(len(w) - 1):
                        gram2 = w[i:i + 2]
                        if self.FREQ.get(gram2):
                            yield (gram2, start + i, start + i + 2)
                if len(w) > 3:
                    for i in xrange(len(w) - 2):
                        gram3 = w[i:i + 3]
                        if self.FREQ.get(gram3):
                            yield (gram3, start + i, start + i + 3)
                yield (w, start, start + width)
                start += width

可以看到,该方法接收三个参数 unicode_sentence,mode,HMM,且后两个都有默认值。

第一部分的 if语句 用于判断unicode_sentence接收的实参是否为unicode编码的str,如果不是就报错。

第二部分就开始切分,(start用以记录单个词的起始位置),使用if else 语句决定使用的模式(default模式和search模式)。

如果参数 mode==‘default’,那么就是用默认模式,使用精确模式切分句子,然后遍历结果,把结果以及它在句子中的位置装在一个元组中返回给迭代器。

如果参数mode!=‘default’,那么使用搜索模式,使用精确模式切分句子,然后遍历结果,把结果中大于2和大于3的再次进行切分,可以成词的结果加上它的位置下标装成元组返回给迭代器,最后返回该值。

搜索模式的源码是不是看起来很眼熟,对,他就是 cut_for_search()的孪生兄弟。

详情参见这一篇

一模一样有没有~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值