首页 > 解决方案 > 如何在 Python 中计算元音和辅音

问题描述

我正在尝试编写一个程序,该程序接受用户输入的句子并在 python 中输出元音和辅音的计数。我的元音计数器工作没有任何问题,但辅音计数总是返回 0。我不知道为什么。

def checkvowelsConsonants():
    consonants = 0
    vowelscount = 0
    index = 0
    sentence = input("Please input your sentence here. This sentence must contain a speical character eg, - ? etc.")
    Vowels = (["a", "e", "i", "o", "u", "A", "E", "I", "O", "U"])
    vowelcount = 0
    while index < len(sentence):
        if sentence[index] in Vowels:
            vowelcount += 1
        index += 1
    while index < len(sentence):
        if sentence[index] not in Vowels:
            consonants += 1
        index += 1
    print("The number of vowels is", vowelcount, "and consonants is", consonants)

这是我收到的参考输出

请在此处输入您的句子。这句话必须包含一个特殊字符,例如 - ? etc.aaaaaaasssssssssss 元音数为 8,辅音数为 0

标签: pythonpython-3.x

解决方案


def classify_letter(string: str):
    vowels = 0
    consonants = 0
    for i in string:
        if i.casefold() in 'aeiou':
            vowels += 1
        elif i.casefold() in 'qwrtypsdfghjklzxcvbnm':
            consonants += 1
    return vowels, consonants

或列表理解

def classify_letter(strng: str) -> tuple:
    x = [i.casefold() in "aeiou" for i in strng if i.casefold() in string.ascii_lowercase]
    return x.count(True), x.count(False)

^ 我承认这可能不是实现它的最佳方式,我愿意接受建议以使其更短和优化!

当通过"hello-"这两个返回时:

(2,3)

推荐阅读