我需要编写一个函数来读取单词中的音节(例如,HAIRY 是 2 个音节)。我的代码显示在底部,我相信它在大多数情况下都能正常工作,因为它适用于我所做的所有其他测试,但不适用于“HAIRY”,它只读为 1 个音节。
def syllable_count(word):
count = 0
vowels = "aeiouy"
if word[0] in vowels:
count += 1
for index in range(1, len(word)):
if word[index] in vowels and word[index - 1] not in vowels:
count += 1
if word.endswith("e"):
count -= 1
if count == 0:
count += 1
return count
测试
print(syllable_count("HAIRY"))
预期:2
收到:1
原文由 Ryan 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题是你给它一个大写字符串,但你只与小写值进行比较。这可以通过将
word = word.lower()
添加到函数的开头来解决。