用逆向最大匹配法实现分词处理(python)

流程图:

# 逆向最大匹配
class IMM(object):
    def __init__(self, dic_path):
        self.dictionary = set()  #定义集合
        self.maximum = 0 #定义最大匹配长度
        with open(dic_path, 'r', encoding='utf-8') as f:   #将存储路径中的语料库打开
            for line in f:
                line = line.strip()  #去除首尾的空白字符
                if not line:
                    continue
                self.dictionary.add(line)  #将遍历的语料库中的元素添加到集合中
                if len(line) > self.maximum:
                    self.maximum = len(line)  #元素长度与最大长度的比较

    def cut(self, text):
        result = []
        index = len(text)
        while index > 0:
            word = None
            for size in range(self.maximum, 0, -1):    由最大长度,逆向遍历
                if index - size < 0:
                    continue
                piece = text[(index - size):index]  #逆向切分
                if piece in self.dictionary:
                    word = piece
                    result.append(word)
                    index -= size
                    break
            if word is None:
                index -= 1
        return result[::-1]

if __name__ == '__main__':
    data_path = ""

    text=‘待切分文本’
    tokenizer = IMM('data_path')
    print(tokenizer.cut(text))

注:这里的语料库需自行查找

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

那个叫马尔的大夫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值