用于在参数中查找元音数量的Python代码

时间:2015-03-15 19:02:17

标签: python

我是一个蟒蛇新手,我正在为我认为简单的代码而苦苦挣扎。我的指示是,写一个函数,它接受一个字符串参数字,并返回字符串中的元音数。

另外,为了澄清,supercat是我的一个字符串参数字。

我已经在这段代码上工作了一段时间,而且它有点混乱。 这就是我到目前为止所拥有的。

vowelletters = ["A","E","I","O","U","a","e","i","o","u"]

def isVowel(supercat):
        if supercat in vowel:
            return True
        else: 
            return False
    print isVowel(supercat)

    def countvowel(supercat):
        count = 0
        for index in super cat:
            if isVowel(vowelletters): count += 1
        return count

    y = countvowel(super cat)
    print(y)

6 个答案:

答案 0 :(得分:1)

您可以先对字符串进行测试lowercase(),这样您就不必检查资本元音(这样可以提高效率)。接下来,您可以count()每个元音在测试字符串中的次数,并使最终sum()得到总数。

vowelletters = ["a","e","i","o","u"]

teststring= "hellO world foo bAr"

count = sum(teststring.lower().count(v) for v in vowelletters)

print count #6

您可以将所有内容放在函数中以轻松重用代码。

def countVowels(mystring):
    vowelletters = ["a","e","i","o","u"]
    return sum(mystring.lower().count(v) for v in vowelletters)

答案 1 :(得分:0)

不允许使用变量名称的空格,我会说:

for index in super cat:

y = countvowel(super cat)

答案 2 :(得分:0)

在我看来,你的缩进有问题,并且你留下了额外的空间。 (超级猫而不是超级猫)

您还在countvowel()中使用了元素而不是索引,并忘记在isVowel()中使用global语句。

vowelletters = ["A","E","I","O","U","a","e","i","o","u"]

def isVowel(supercat):
    global vowelletters
    if supercat in vowelletters:
        return True
    else: 
        return False
    print isVowel(supercat) # This isn't executed
            # because it is after a return statement.

def countvowel(supercat):
    count = 0
    for index in supercat:
        if isVowel(index): count += 1
    return count

y = countvowel("supercat")
print(y)

答案 3 :(得分:0)

您可以简化您正在编写的此功能

def countvowel(supercat):

    count = 0
    for i in range(len(supercat)-1):
        if supercat[i] in "AEIOUaeiou":
            count += 1

    print(count)

答案 4 :(得分:0)

怎么样:

vowelletters = ("a","e","i","o","u")

def countvowel(word):
    word = word.lower()

    count = 0
    for char in word:
        if char in vowelletters:
            count += 1

    return count

print countvowel('super cat')  # prints 3

或使用列表理解:

vowelletters = ("a","e","i","o","u")


def countvowel(word):
    word = word.lower()

    vowels = [char for char in word if char in vowelletters]
    return len(vowels)

答案 5 :(得分:0)

您可以使用sum()和一个生成器。

def countVowels(word):
    return sum(1 for c in word if c in "AEIOUaeiou")

print(countVowels('supercat'))