Python中的音节计数 [英] Syllable Count In Python

查看:56
本文介绍了Python中的音节计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要编写一个函数来读取单词中的音节(例如,HAIRY是2个音节).我的代码显示在底部,我相信它可以在大多数情况下使用,因为它可以与我完成的所有其他测试一起使用,但不适用于"HAIRY",因为它只能读为1个音节.

I need to write a function that will read syllables in a word (for example, HAIRY is 2 syllables). I have my code shown on the bottom and I'm confident it works in most cases, because it works with every other test I've done, but not with "HAIRY" where it only reads as 1 syllable.

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

推荐答案

问题是您给它提供了大写的字符串,但只与小写的值进行了比较.可以通过在函数的开头添加 word = word.lower()来解决此问题.

The problem is that you're giving it an uppercase string, but you only compare to lowercase values. This can be fixed by adding word = word.lower() to the start of your function.

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 count == 0:
        count += 1
    return count

print(syllable_count('HAIRY'))  # prints "2"

这篇关于Python中的音节计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆