zoukankan      html  css  js  c++  java
  • 最大匹配算法进行分词 前向 后向 python实现

    # 先定义个词典
    word_dict = ['我们', '经常', '有','有意见','意见','分歧']
    # 滑动窗口的大小
    max_len = 5 
    # 用户的输入
    user_input = '我们经常有意见分歧'
    len(user_input)
    结果:
    9
    

     前向最大匹配算法的实现

    # 前向最大匹配算法
    result = []
    i = 0 
    while i < len(user_input): 
        matched = False 
        pos = i + max_len if i + max_len < len(user_input) else len(user_input)
        while user_input[i:pos] not in word_dict and i < pos:
            print(user_input[i:pos]) 
            pos -= 1 
        if i < pos: 
            matched = True
            result.append(user_input[i:pos])
        i = pos if matched == True else i + max_len         
    print(result)
    

    输出结果:

    我们经常有
    我们经常
    我们经
    经常有意见
    经常有意
    经常有
    有意见分歧
    有意见分
    ['我们', '经常', '有意见', '分歧']


    后向最大匹配算法的实现
    # 后向最大匹配算法 
    result = []
    i = len(user_input) 
    while i > 0: 
        matched = False 
        pos = i - max_len if i - max_len > 0 else 0 
        while user_input[pos:i] not in word_dict and i > pos:
            print(user_input[pos:i]) 
            pos += 1      
        if i > pos:
            matched = True 
            result.insert(0, user_input[pos:i])
        i = pos if matched == True else i - max_len
    print(result) 
    

    输出结果:

    有意见分歧
    意见分歧
    见分歧
    经常有意见
    常有意见
    我们经常
    们经常
    ['我们', '经常', '有意见', '分歧']
  • 相关阅读:
    python多线程http压力测试脚本
    php随机生成国内ip
    HTTP请求方式中8种请求方法(简单介绍)
    PHP函数
    jquery获取span标签下的第一个span子标签内容
    php实现数据库备份导出成sql
    php实现备份数据库
    中文繁体简体问题
    编程素养Day009
    编程素养Day008
  • 原文地址:https://www.cnblogs.com/carlber/p/12148024.html
Copyright © 2011-2022 走看看