我是初学者,我有一个需要帮助的问题.它是功课,所以任何提示都受到赞赏.我看过一些类似的话题,但答案超出了我所知道的怎么做......
我需要计算文本文件中音节的数量,作为更大程序的一部分.除了音节,我有我需要的一切.我尝试了几种不同的方法,但它并不总能捕捉特殊情况.我应该'计算相邻元音的组,不包括单词末尾的'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
Run Code Online (Sandbox Code Playgroud)
编辑:新代码
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
Run Code Online (Sandbox Code Playgroud)
只是一个建议,但不是"寻找"相邻的元音,你不能在每次遇到一个单词的开头或单词中的辅音发生的初始元音时递增你的'计数',除了'e' '在一个单词的末尾(除非你的计数为零).为了澄清,每当遇到相邻的元音时,只有第一个元音会增加你的计数.
不是积极的它会起作用,但我认为它适用于我刚写的所有单词.
祝好运.
| 归档时间: |
|
| 查看次数: |
10360 次 |
| 最近记录: |