HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonCritical

Counting all the vowels in a passage of text

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
passagethecountingvowelsalltext

Problem

My son just started high school and in Math, he was asked to do some stats homework. The exercise was to count all the vowels in a passage of text, then answer some questions about frequency.

Out of curiosity, I wrote a quick Python script to count the vowels:

text = "Australian Rules Football is a ball game played by two teams of eighteen players with an ellipsoid ball on a large oval field with four upright posts at each end. Each team attempts to score points by kicking the ball through the appropriate posts (goals) and prevent their opponents from scoring. The team scoring the most points in a given time is the winner. Usually this period is divided into four quarters of play.Play begins at the beginning of a quarter or after a goal, with a tap contest between two opposing players (rucks) in the centre of the ground after the umpire either throws the ball up or bounces it down."

vowels = {'a':0, 'e':0, 'i':0, 'o':0, 'u':0}

for t in text:
    if t.lower() == 'a':
        vowels['a'] = 1 + vowels['a']
    elif t.lower() == 'e':
        vowels['e'] = 1 + vowels['e']
    elif t.lower() == 'i':
        vowels['i'] = 1 + vowels['i']
    elif t.lower() == 'o':
        vowels['o'] = 1 + vowels['o']
    elif t.lower() == 'u':
        vowels['u'] = 1 + vowels['u']

print vowels


I don't claim to be very good at Python. I enjoy mucking around with it, but I think I'm missing something here. The script works, but I'm clearly repeating myself in the for loop. What's the better "Pythonic" was for me to have done this?

Solution


  • Change to lower once: text.lower() instead of t.lower() inside loop.



  • Use t in vowels to check if the character is vowels.



-
vowels = {...} can be replaced with dict.fromkeys('aeiou', 0) (See dict.fromkeys)

Caution: Use this only if the value is immutable.

>>> dict.fromkeys('aeiou', 0)
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}


vowels = dict.fromkeys('aeiou', 0)

for t in text.lower():  # Change to lower once.
    if t in vowels:
        vowels[t] += 1

print vowels


Alternatively, you can use try ... except KeyError ...:

for t in text.lower():  # Change to lower once.
    try:
        vowels[t] += 1
    except KeyError:  # Ignore consonants.
        pass


Or using battery included, collections.Counter:

from collections import Counter
vowels = Counter(c for c in text.lower() if c in 'aeiou')
# => Counter({'e': 54, 'a': 41, 'o': 40, 'i': 37, 'u': 14})

Code Snippets

>>> dict.fromkeys('aeiou', 0)
{'a': 0, 'i': 0, 'e': 0, 'u': 0, 'o': 0}
vowels = dict.fromkeys('aeiou', 0)

for t in text.lower():  # Change to lower once.
    if t in vowels:
        vowels[t] += 1

print vowels
for t in text.lower():  # Change to lower once.
    try:
        vowels[t] += 1
    except KeyError:  # Ignore consonants.
        pass
from collections import Counter
vowels = Counter(c for c in text.lower() if c in 'aeiou')
# => Counter({'e': 54, 'a': 41, 'o': 40, 'i': 37, 'u': 14})

Context

StackExchange Code Review Q#124534, answer score: 84

Revisions (0)

No revisions yet.