计算一个单词的音节数

2024-09-28 21:24:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我是个初学者,我有一个问题需要帮助。这是家庭作业,所以任何提示都是值得赞赏的。我也看到过一些类似的话题,但答案超出了我所知道的范围。。。

作为大型程序的一部分,我需要计算文本文件中的音节数。除了音节我什么都有。我试过几种不同的方法,但并不总是能抓住特殊情况。我应该“数一组相邻的元音,不包括单词末尾的‘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

Tags: in程序forindexifdefcountword
1条回答
网友
1楼 · 发布于 2024-09-28 21:24:22

只是一个建议,而不是“寻找”相邻的元音,你能不能不增加你的'计数',每次你遇到的初始元音,无论是在一个词的开头或在一个辅音之后,除了'e'在一个词的结尾(除非你的计数是零的那个词)。为了澄清,每当你遇到相邻的元音,只有第一个元音会增加你的计数。

不是很肯定,但我觉得这对我刚写的所有单词都有效。

祝你好运。

相关问题 更多 >