python - 实现 Soundex 编码算法
问题描述
Soundex是一种语音算法,它将一个单词编码为一个字母,后跟三个数字,粗略地描述这个单词的发音。发音相似的单词具有相同的四字符代码。例如,单词 Carrot 和 Caret 都编码为 C123。Soundex 编码算法的细微变化如下:
- 保留第一个字母。
- 对于剩余的字母,删除所有出现的 a、e、i、o、u、h、y 和 w。
- 将数字分配给剩余的其他字母,以便
- b、f、p 和 v → 1
- c、g、j、k、9、s、x 和 z → 2
- d 和 t 都 → 3
- l ('el') → 4
- m 和 n → 5
- r → 6
- 如果在原始完整单词中两个或多个已被相同数字替换的字母彼此相邻,则只保留其中的第一个。
- 只保留剩下的前四个字符。如果少于四个,则在末尾添加零以使字符串的长度为四。编写一个执行该算法的程序。
样本输出:
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))
解决方案
第 24 行中字符串 'r' 周围缺少引号:
elif string[i] == 'r' :
推荐阅读
- excel - 将具有类别和值的列拆分为两列
- amazon-web-services - aws-access(npm 工具)只在默认 vpc 的安全组中添加 ip 地址
- python - 错误:运行 Octave 时,'python_ipc_popen2' 在第 62 行第 62 列附近未定义
- c# - 生成 Excel 文件期间的 MemoryStream 读取超时
- javascript - Next js AMP amp-onetap-google 不工作
- reactjs - 将 Redux 转换为 React Context API + useReducer
- c++ - 为什么在类声明之后放置 dllexport 会消除 C++ 中的 C4251 警告
- javascript - MessageEmbed 字段值必须是非空字符串
- vue.js - 将数据传递给其他组件vue,不起作用
- ethereum - 交易完成,但 NFT 未转移