中文分词-前向最大匹配和后向最大匹配

 

例子:sentence = "我是一名计算机专业的学生"

词典:["我", "是", "一", "一名", "计算机", "的", "学生", "专业"]

前向最大匹配

给定max_length = 5

首先判断word = “我是一名计”,是否在词典中,不在,word减去右边一个词,word = “我是一名”,继续判断word是否在词典中,不在,word减去右边一个词,word = "我是一“,继续判断word是否在词典中,不在,word减去右边一个词,word = "我是”,继续判断word是否在词典中,不在,word减去右边一个词,word = "我“,在词典中;接下来从”是“开始,word = "是一名计算",按照上述思路继续判断,得到”是“,依次内推,得到结果”一名“,”计算机“,”专业“,”的“,”学生“。分词结果为:

['我', '是', '一名', '计算机', '专业', '的', '学生']

反向最大匹配

首先判断word = ”专业的学生“,是否在词典中,不在,word减去左边一个词,word = "业的学生”,继续判断word是否在词典中,不在,word减去右边一个词,word = "的学生“,继续判断word是否在词典中,不在,word减去右边一个词,word = ”学生“,在词典中,得到结果“学生”;接下来从word = "算机专业的"开始,继续按照上述思路进行判断,因此最后得到结果为:

['学生', '的', '专业', '计算机', '一名', '是', '我']

python代码如下:

"""
中文分词:前向最大匹配+后向最大匹配
"""
dic = ["我", "是", "一", "一名", "计算机", "的", "学生", "专业"]
sentence = "我是一名计算机专业的学生"
max_length = 5

def forwardMaxmatching(sentence):
    res = []
    sentence = sentence
    len_sentence = len(sentence)
    while len_sentence > 0:
        word = sentence[0:max_length]
        while word not in dic:
            if len(word) == 1:
                break
            word = word[0:len(word) - 1]
        res.append(word)
        sentence = sentence[len(word):]
        len_sentence = len(sentence)
    return res
print(forwardMaxmatching(sentence))

def backwordMaxmatching(sentence):
    res = []
    sentence = sentence
    len_sentence = len(sentence)
    while len_sentence > 0:
        word = sentence[-max_length:]
        while word not in dic:
            if len(word) == 1:
                break
            word = word[-(len(word) - 1):]
        res.append(word)
        sentence = sentence[:-len(word)]
        len_sentence = len(sentence)
    return res
print(backwordMaxmatching(sentence))

github 地址:https://github.com/cantaloupeJinJin/NLPlearning

如果觉得还不错,欢迎star   ?

 

你可能感兴趣的:(自然语言处理)