Count the characters, words, sentences and vowels in a piece of Python text.
Each count needs a different tool, and choosing the right one is the real skill that this question tests.
import re
text = "Python is easy-to-learn, and it's fast."
print(len(text)) # 39 characters
print(len(text.split())) # 6 words split on spaces
print(len(re.findall(r"[A-Za-z']+", text))) # 8 word-like tokens
print(len(re.findall(r"[.!?]", text))) # 1 sentence
vowels = 0
for letter in text.lower():
if letter in 'aeiou':
vowels = vowels + 1
print('vowels ->', vowels) # 10 vowelsThe character count is simply the length of the string. It counts code points rather than bytes, so an accented letter counts as one character.
The two word counts are different from each other, and the difference is the interesting part. split() splits on whitespace and keeps the punctuation attached to each word, so easy-to-learn, comes out as a single piece. The regular expression finds runs of letters and apostrophes, so easy-to-learn becomes three tokens and the trailing comma disappears. Neither answer is wrong. You have to decide what a word means for your data before you can pick the right method.
Counting sentences with a regular expression over the punctuation marks is a quick approximation, but it is fooled by an abbreviation or by a decimal point. A real sentence splitter needs a library, and it is worth saying that out loud instead of pretending that the regular expression is exact.
The vowel count uses a plain loop, which is easy to read and easy to change. The shorter alternative is a generator expression inside sum(), which is the idiomatic way to count the items that satisfy a condition, and it is worth knowing both forms.