python实现Soundex算法

Soundex是一种语音算法,利用英文字的读音计算近似值,值由四个字符构成,第一个字符为英文字母,后三个为数字。在拼音文字中有时会有会念但不能拼出正确字的情形,可用Soundex做类似模糊匹配的效果。例如Knuth和Kant二个字符串,它们的Soundex值都是“K530”。其在电脑大师高德纳名著《计算机程序设计艺术》都有详细的介绍。(引用于Wikipedia 中文版
我这里用比较简单的方式实现该算法,不需要很好的水平即可看懂。

def Soundex(string):
    string = string.lower()
    law = {'aehiouwy' : 0,
           'bfpv': 1,
           'cgjkqsxz': 2,
           'dt': 3,
           'l': 4,
           'mn': 5,
           'r': 6}
    temp_string = string
    for key, value in law.items():
        temp_string = re.sub('[{}]'.format(key), str(value), temp_string)
    temp_string = re.sub('0', '', temp_string)
    result = []
    for char in temp_string:
        if char not in result:
            result.append(char)

    result = string[0] + ''.join(result[:3])
    while len(result) != 4:
        result += '0'
    print(result)
发布了12 篇原创文章 · 获赞 3 · 访问量 2055

猜你喜欢

转载自blog.csdn.net/weixin_40902563/article/details/105382376