BMM 和 FMM 中文分词

分词题目出自 : https://blog.csdn.net/xubo245/article/details/12917745,感谢博主呢

phrase_dict = ('的确','王公','实在','在理','公子')
max_len = 5

'''
BMM :其主要思想 注释已经给出
'''
def BMM(sentence , split_str):
'''
sentence: 待分词 语句
split_str: 分词分割符,没有用到
return: 
'''
    print(phrase_dict, type(phrase_dict))
    print("sentence -> " , sentence)

    segment_list = []

    while sentence:
        if len(sentence) >= max_len:
            temp = sentence[ : max_len] # 截取最长的词
        else:
            temp = sentence
        while len(temp) > 1: # 判断 当前的词总长度是否大于 1
            if temp in phrase_dict: # 判断当前 词 是否在字典中
                segment_list.append(temp) # 加入 到 记录 分词的 列表 中
                break # 如果在字典中,则 立刻 退出 当前的 循环
            temp = temp[:-1] # 不在 字典中,则 从 后面向前 移动一个字

        if len(temp) == 1: # 如果当前的 词 长度 为 1 , 则表示在字典中未找到,一个字为一个词
            segment_list.append(temp) # 将当前的 temp 加入到 词 列表中
        sentence = sentence[len(temp) :] # 这时,在原来的句子中,将分出的词删掉,继续

    print(segment_list)


'''
FMM 中文分词,其主要思想已经在注释中给出
'''
def FMM(sentence , split_str):# 参数含义类 BMM

    print(phrase_dict, type(phrase_dict))
    print("sentence -> ", sentence)

    segment_list = []

    while sentence:
        if len(sentence) > max_len:
            temp = sentence[len(sentence) - max_len :]  # 截取最长的词
        else:
            temp = sentence
        while len(temp) > 1:  # 判断当前的词总长度是否大于
            if temp in phrase_dict:  # 判断当前词是否在字典中
                segment_list.append(temp)  # 加入到记录分词的列表中
                break  # 如果在字典中,则立刻退出当前的循环
            temp = temp[1:]  # 不在字典中,则从前向后移动一个字

        if len(temp) == 1:  # 如果当前的词长度为1,则表示在字典中未找到,一个字为一个词
            segment_list.append(temp)  # 将当前的 temp 加入到词列表中
        sentence = sentence[: len(sentence) - len(temp)]  # 这时,在原来的句子中,将分出的词删掉,继续

    segment_list.reverse()
    print(segment_list)

def BDMM():
    pass

if __name__ == "__main__":
    sentence  = "王公子说的确实在理"
    BMM(sentence ,  " ")
    print(" - " * 100)
    FMM(sentence , " ")

经过对上述代码进行改变输入格式,加入第一趟分词的步骤输出,其输出结果如下

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值