求助修复夏威夷单词发音程序:阻止重复值追加问题
修复夏威夷单词发音程序的元音对重复处理问题
问题根源
你的程序核心问题是匹配到元音对后,没有跳过已被使用的第二个字符,导致同一个字符被重复处理:
- 处理「Keiki」时,当x=1(字符'e')匹配到「ei」元音对,程序添加了"ay"但x只+1,下一次循环x=2又处理字符'i',额外添加了"ee",最终输出多了"ee"变成「Kayee-kee」
- 处理「Maui」时,「au」匹配成"ow"后,x继续+1处理'u'添加"oo",再处理'i'添加"ee",导致输出「Mowooeyee」
另外还有个逻辑错误:elif (first == 'i' or 'e') and second == 'w' 中,'e'是布尔真值,这个条件会被错误触发,应该改为first == 'i' or first == 'e'。
修复后的代码
execute = True answer = [] word = str(input('Enter a hawaiian word: ')).lower() vowels = {'a':'ah', 'e':'eh', 'i':'ee', 'o':'oh', 'u':'oo'} pairs = {'ai':'eye', 'ae':'eye', 'ao':'ow', 'au':'ow', 'ei':'ay', 'eu':'eh-oo', 'iu':'ew', 'oi':'oy', 'ou':'ow', 'ui':'ooey'} x = 0 while x < len(word): valid = ['a', 'e', 'i', 'o', 'u', 'p', 'k', 'h', 'l', 'm', 'n', 'w', "`", ' ', "'"] first = str(word[x]) if first not in valid: print(f'Invalid word, {word[x]} is not a valid hawaiian character.') execute = False break else: try: second = word[x+1] except IndexError: second = None pair = pairs.get(f"{first}{second}") if second is not None else None if first in vowels: if pair: answer.append(pair) # 匹配到元音对,跳过第二个字符 x += 2 # 只有不是最后一个字符时才加连字符 if x < len(word) and word[x] not in ["'", " "]: answer.append('-') continue # 跳过后续逻辑,直接进入下一次循环 elif (first == 'i' or first == 'e') and second == 'w': answer.append(f"{vowels[first]}-v") x += 1 if second is not None and second not in ["'", " "]: answer.append('-') else: answer.append(vowels[first]) x += 1 if x < len(word) and word[x] not in ["'", " "]: answer.append('-') else: if first != 'w': answer.append(first) x += 1 # 辅音后如果是元音(非特殊字符)才加连字符 if x < len(word) and word[x] in vowels and word[x] not in ["'", " "]: answer.append('-') if execute: # 优化音节首字母大写格式 pronunciation = '-'.join([part.capitalize() for part in ''.join(answer).split('-')]) print(f'{word.upper()} is pronounced {pronunciation}')
关键修改说明
- 匹配到元音对时,通过
x += 2跳过第二个字符,彻底避免重复处理 - 修正
i/e + w的条件判断逻辑,确保只有字符是'i'或'e'时才触发 - 调整连字符添加逻辑:仅当后续还有有效发音字符时才添加,避免结尾出现多余连字符
- 优化发音结果的格式:每个音节单独首字母大写,更符合示例中的「Ah-loh-hah」风格
内容的提问来源于stack exchange,提问作者Csky1-88
相关产品推荐
相关产品推荐

