Count vowels and know how many there are

3

Good! I want to create a function that would allow me to say if a word or phrase has vowels, and if so, how many vowels it has, but I have 2 problems in my code that I do not understand:

def conta_vogais(str):
    vogais = ['a','e','i','o','u']
    if str.lower() in vogais:
        return True
        vogais.count('a','e','i','o','u')
    else:
        return False

When I run the program, it seems to accept no more than one letter to run the if statement and qd I put only one letter tb n tells me the value of the count. Can anyone help me?

    
asked by anonymous 19.11.2016 / 17:02

2 answers

4

There is a class in Python called Counter . With it you can do it efficiently and without reinventing the wheel.

import re
from collections import Counter
def vogais(string):
    return Counter(re.sub('[^aeiouAEIOU]', '', string))
    
19.11.2016 / 19:33
2

You can do this:

1.

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    result = {}
    vogais = 'aeiou'
    for i in vogais:
        if i in string:
            result[i] = string.count(i)
    return result

print(conta_vogais('olaaa'))

Or by doing dictinary compreension enough ::

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    vogais = 'aeiou'
    return {i: string.count(i) for i in vogais if i in string}

print(conta_vogais('olaaa'))

Output:

  

{'a': 3, 'o': 1}


2.

I made the above example so that it counted and returned the number of times it appears, and only if it appears. But if you just want the total number of vowels you can:

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    result = 0
    vogais = 'aeiou'
    for i in vogais:
        result += string.count(i)
    return result

print(conta_vogais('olaaa'))

OU:

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    vogais = 'aeiou'
    return sum(string.count(i) for i in vogais)

print(conta_vogais('olaaa'))

What will happen, in this case 4


3.

Now, to complete the answer a little more, you can also return the number of times each appears (the ones that do not even appear):

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    result = {}
    vogais = 'aeiou'
    for i in vogais:
        result[i] = string.count(i)
    return result

print(conta_vogais('olaaa'))

Or by doing dictinary compreension just:

def conta_vogais(string):
    string = string.lower() # para que a comparação não seja sensível a maiuscula/minuscula
    vogais = 'aeiou'
    return {i: string.count(i) for i in vogais}

print(conta_vogais('olaaa'))

Output:

  

{'a': 3, 'e': 0, 'u': 0, 'i': 0, 'o': 1}

    
19.11.2016 / 17:10