我是个初学者,我有一个问题需要帮助。这是家庭作业,所以任何提示都是值得赞赏的。我也看到过一些类似的话题,但答案超出了我所知道的范围。。。
作为大型程序的一部分,我需要计算文本文件中的音节数。除了音节我什么都有。我试过几种不同的方法,但并不总是能抓住特殊情况。我应该“数一组相邻的元音,不包括单词末尾的‘e’”,我明白这意味着什么,但我无法在程序中正确地计算。这是我所拥有的:def syllables(word):
syl = 0
vowels = 'aeiouy'
starts = ['ou','ei','ae','ea','eu','oi']
endings = ['es','ed','e']
word = word.lower().strip(".:;?!")
for vowel in vowels:
syl +=word.count(vowel)
for ending in endings:
if word.endswith(ending):
syl -=1
for start in starts:
if word.startswith(start):
syl -=1
if word.endswith('le'):
syl +=1
if syl == 0:
syl+=1
return syl
编辑:新代码def syllables(word):
count = 0
vowels = 'aeiouy'
word = word.lower().strip(".:;?!")
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 count == 0:
count +=1
return count