首页 > 解决方案 > 实现 Soundex 编码算法

问题描述

Soundex是一种语音算法,它将一个单词编码为一个字母,后跟三个数字,粗略地描述这个单词的发音。发音相似的单词具有相同的四字符代码。例如,单词 Carrot 和 Caret 都编码为 C123。Soundex 编码算法的细微变化如下:

样本输出:

Enter a word to code: Robert
The coded word is R163.

代码:

def soundexCode(string):
    result = string[0] +""
    for i in range(1, len(string)):
        if(string[i] == 'b' or string[i] == 'f' or string[i] == 'p' or
           string[i] == 'v'):
            if(result[-1]!= '1'):
                result = result + '1';

        elif (string[i] == 'c' or string[i] == 'g' or string[i] == 'j' or
              string[i] == 'k' or string[i] == 'q' or string[i] == 's' or
              string[i] == 'x' or string[i] == 'z'):
            if (result[-1] != '2'):
                result = result +'2';

        elif string[i] == 'd' or string[i] == 't':
            if (result[-1] != '3'):
                result = result + '3';

        elif string[i] == 'l' :
            if (result[-1] != '4'):
                result = result + '4';

        elif string[i] == 'm' or string[i]== 'n' :
            if(result[-1] != '5'):
                result = result + '5';

        elif string[i] == r :
            if result[-1] != '6':
                result = result + '6';

    return result

    word = input ('Enter a word to code : ')
    print("\nThe coded word is " + soundexCode(word))

标签: pythonsoundex

解决方案


第 24 行中字符串 'r' 周围缺少引号:

    elif string[i] == 'r' :

推荐阅读