中文语序识别的方法一

一、前言

        语序识别的两个思路:1.依据分词器收录的词语进行匹配查询; 2.依据海量词向量进行预测实现。

二、主要思路

        本文用第一种方法实现一下,主要思路如下:

1.检查输入的字符串,并将各字随机排列组合生成不同的“词语”;

2.将1中的词语在分词器的词库中进行匹配,返回词频;

3.选择词频最大的词语作为正确的语序进行返回。

三、实现代码

import jieba
from itertools import permutations

# 获得汉字的所有排列方式
def get_all_possible_word(str):
    word_list = list(permutations(str))
    for i in range(len(word_list)):
        word_list[i] = ''.join(word_list[i])
    return word_list


# 寻找列表中最长的词
def find_longest(list):
    l = 0
    index = 0
    for i, word in enumerate(list):
        if len(word) > l:
            l = len(word)
            index = i
    return index


# 输入词列表,返回结巴分词内词频最高的词
def find_highest_frequency(possible_words):
    word_dict = dicts(r'C:\Users\Simon\AppData\Local\Programs\Python\Python36\Lib\site-packages\jieba\dict.txt')
    possible_dict = {}
    for possible_word in possible_words:
        possible_dict[word_dict[possible_word]] = possible_word
    sorted = sort_dict_by_key(possible_dict)

# 对输入的字典根据key大小排序
def sort_dict_by_key(dic):
    return [(k, dic[k]) for k in sorted(dic.keys())]

# 将dict.txt转换为字典
def dicts(filename):
    with open(filename) as f:
        array_lines = f.readlines()
    Dict = {}
    for line in array_lines:
        line = line.strip()
        listFromLine = line.split()
        Dict[listFromLine[0]] = int(listFromLine[1])
    return Dict

# 语序识别
def recog_word_order(str):
    l = len(str)
    word_list = get_all_possible_word(str)
    possible_words = []
    for word in word_list:
        seg_list = jieba.lcut(word, cut_all=True)
        print(seg_list)
        index = find_longest(seg_list)
        if len(seg_list[index]) == l:
            possible_words.append(seg_list[index])
    if len(possible_words) == 1:
        return possible_words[0]
    elif len(possible_words) > 1:
        return find_highest_frequency(possible_words)
    else:
        return "jieba暂未收录该词语"

四、效果

测试效果还不错,如下:

五、后记

        本方法识别语序简单快捷,整体效果还是不错的。但该法高度依赖jieba的词库,如果需要检测的词语不在词库中,只需要手动添加到该词库中即可,识别正确率会越来越高。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值