Reputation: 99
Trying to figure out the best way in Python to allow a user to input a sentence, and then calculate the number of characters in that sentence, in addition to calculating the number of vowels. I want the output to return the total number of characters, plus the total number of A's, the total number of O's, the total number of U's etc. Here is the code I have so far:
# prompt for input
sentence = input('Enter a sentence: ')
# count of the number of a/A occurrences in the sentence
a_count = 0
# count of the number of e/E occurrences in the sentence
e_count = 0
# count of the number of i/I occurrences in the sentence
i_count = 0
# count of the number of o/O occurrences in the sentence
o_count = 0
# count of the number of u/U occurrences in the sentence
u_count = 0
# determine the vowel counts and total character count
length=len(sentence)
if "A" or "a" in sentence :
a_count = a_count + 1
if "E" or "e" in sentence :
e_count = e_count + 1
if "I" or "i" in sentence :
i_count = i_count + 1
if "O" or "o" in sentence :
o_count = o_count + 1
if "U" or "u" in sentence :
u_count = u_count + 1
#Display total number of characters in sentence
print("The sentence", sentence, "has", length,"characters, and they are\n",
a_count, " a's\n",
e_count, "e's\n",
i_count, "i's\n",
o_count, "o's\n",
u_count, "u's")
The problem is when I run this I just get one character for each vowel, which means that my code isn't actually counting up the individual vowels the way I want it to. Anyone input how to fix this based on the code I have presented would be appreciated
Upvotes: 4
Views: 13204
Reputation: 1855
Count the letters using Counter from collections module and then just iterate over the counter, if the letter is vowel, add its count to the vowel_count.
from collections import Counter
counts = Counter(input('Enter a sentence: '))
vowel_count = 0
for letter in counts:
if letter in ['A', 'E', 'I', 'O', 'U', 'a', 'e', 'i', 'o', 'u']:
vowel_count += counts[letter]
For example to get the total count of (A, a)'s you would do:
print('Count of A\'s is: {}'.format(counts['A'] + counts['a']))
Upvotes: 5