我需要编写一个函数来读取单词中的音节(例如,HAIRY是2个音节)。我的代码显示在底部,我相信它在大多数情况下都能工作,因为它可以与我做过的所有其他测试一起工作,但不能与“HAIRY”一起工作,因为它只能读一个音节。
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
音节检测有一定的规则,您可以从网站查看规则:Counting Syllables in the English Language Using Python
下面是python代码:
你的代码在小写的情况下似乎运行良好。不过,如果你用大写字母传递一个单词,它将始终返回1。这是因为你在测试“aeiou”而不是“aeiouAEIOU”。 你可以用几种方法来解决这个问题。
例1:
例2:
示例3:在“音节计数”函数的开头添加这行代码
问题是,您给它一个大写字符串,但只与小写值进行比较。这可以通过在函数的开头添加
word = word.lower()
来解决。相关问题 更多 >
编程相关推荐