我试图让我的基本音节计数器通过多个单词运行,但我不知道如何做到这一点而不会出错。在下面的代码中,我创建了一个包含两个单词的占位符变量,供代码计数音节。但是,代码最终无法运行,也不会创建任何输出。有人知道该怎么做吗?
new_variable = "WORD", "AGAIN"
def syllable_count(word):
word = word.lower()
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 word.endswith("le"):
count += 1
if word.endswith("ia"):
count += 1
if count == 0:
count += 1
if word.endswith("management"):
count -= 1
if word.endswith("announcement"):
count -= 1
return count
print(syllable_count(new_variable))
正如@TimRoberts在评论中提到的。你正在传递一个元组而不是字符串给你的syllable_counter
函数。
你所需要做的就是遍历元组,即new_varieble
,然后为每个值调用syllable_counter
。
去掉最后一行,写这两行:
for word in new_variable:
print(syllable_counter(word))
new_variable = "WORD", "AGAIN"
print(new_variable)
('WORD', 'AGAIN')
你可以尝试遍历列表替换为new_variable,例如:
for new_variable in ["WORD", "AGAIN"]:
print(syllable_count(new_variable))