我需要编写一个函数来读取单词中的音节(例如,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
Run Code Online (Sandbox Code Playgroud)
测试
print(syllable_count("HAIRY"))
Run Code Online (Sandbox Code Playgroud)
预期:2
收到:1