作业二:使用前向/后向算法实现中文分词器|自然语言

具体的前向、后向算法可见此链接

源代码

import re

#前向算法
def MMseg_cut(sentence, dictA):
    # sentence:要分词的句子
    #dictA:机器词典
    
    result = [] #存放分好的词
    sentenceLen = len(sentence) #待分词字段长度
    n = 0
    maxDictA = max([len(word) for word in dictA])  #取词典中最长词条的字符长度

    while sentenceLen>0:
        maxCutLen = min(maxDictA,sentenceLen)  #如果当前字段长度小于词典最长字段长度时,取当前字段长度进行划分
        sub_sen = sentence[0:maxCutLen]
        while maxCutLen>0:
            if sub_sen in dictA:
                result.append(sub_sen)
                break
            elif len(sub_sen)==1: 
            #长度为1说明词典中并无此词,则直接放入result中
                result.append(sub_sen)
                break
            else:
                #否则,删去最后一个字,重新操作
                maxCutLen-=1
                sub_sen = sub_sen[0:maxCutLen]
        #更新当前未匹配字段及其长度
        sentence = sentence[maxCutLen:]
        sentenceLen -=maxCutLen                
    
    print("前向划分结果为:",result)  # 输出分词结果

#后向算法
def RMMseg_cut(sentence,dictB):
    # sentence:要分词的句子
    #dictA:机器词典
    
    result = []
    sentenceLen = len(sentence)
    maxDictB = max([len(word) for word in dictB])

    while sentenceLen>0:
        maxCutLen = min(sentenceLen,maxDictB)
        sub_sen = sentence[-maxCutLen:]
        while maxCutLen>0:
            if sub_sen in dictB:
                result.append(sub_sen)
                break
            elif len(sub_sen)==1:
                result.append(sub_sen)
                break
            else:
                maxCutLen-=1
                sub_sen = sub_sen[-maxCutLen:]
        sentence = sentence[0:-maxCutLen]
        sentenceLen -= maxCutLen

    print("后向划分结果为:",result[::-1],end="")

#得到字典
def get_dict(file_path):
    f = open(file_path,"r", encoding='utf-8',errors='ignore')
    dictA = {}
    for lines in f.readlines():
        lines =re.findall('[\u4e00-\u9fa5]+',lines)
        for line in lines:
            if line not in dictA:
                dictA[line] = 1
            else:
                dictA[line] += 1
    return dictA

#主函数
if __name__=='__main__':
    #词库地址
    dataSet_path = "E://大三上//自然语言//实验//111186763ciku//中文分词词库整理//dict.txt"
    #获得词典
    dictA = get_dict(dataSet_path)
    n = int(input("输入你想划分的句子条数:"))
    while(n):
        sentence = input()
        MMseg_cut(sentence, dictA)
        RMMseg_cut(sentence, dictA)
        n -= 1

程序运行结果

在这里插入图片描述

(1)可以看出当词库非常庞大时,使用前向、后向算法构建的简单中文分词器并不能很好的解决组合型切分歧义问题。

(2)词库可以自己进行选择,只要存入字典中即可。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

比奇堡咻飞兜

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

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

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

打赏作者

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

抵扣说明:

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

余额充值