Reputation: 4195
I've found a few instances of this but my question is slightly different.
I need to scan a sentence like
For letter in sentence
if letter == "a" or letter == "A": letterATotal = letterATotal + 1
elif letter == "e" or letter == "E": letterETotal = letterETotal + 1
etc all the way to U. But then I need to compare them all and print the line containing the most frequent so "the most frequent vowel is A occurring 5 times". Problem is I don't know how to display the actual letter. I can only display the number. Any ideas?
Upvotes: 0
Views: 394
Reputation: 371
the following code works if you are using Python 3 or above:
s = input ('Enter a word or sentence to find how many vowels:')
sub1 = 'a'
sub2 = 'e'
sub3 = 'i'
sub4 = 'o'
sub5 = 'u'
print ('The word you entered: ', s)
print ('The count for a: ', s.count(sub1))
print ('The count for e: ', s.count(sub2))
print ('The count for i: ', s.count(sub3))
print ('The count for o: ', s.count(sub4))
print ('The count for u: ', s.count(sub5))
Upvotes: 0
Reputation:
Look at this:
>>> from collections import Counter
>>> mystr = "AaAaaEeEiOoouuu"
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
>>> "the most frequent vowel is {} occurring {} times".format(a.upper(), b)
'the most frequent vowel is A occurring 5 times'
>>>
Here is a reference on collections.Counter
.
Edit:
Here is a step-by-step demonstration of what's going on:
>>> from collections import Counter
>>> mystr = "AaAaaEeEiOoouuu"
>>> Counter(c for c in mystr.lower() if c in "aeiou")
Counter({'a': 5, 'o': 3, 'e': 3, 'u': 3, 'i': 1})
>>> # Get the top three most common
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(3)
[('a', 5), ('o', 3), ('e', 3)]
>>> # Get the most common
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)
[('a', 5)]
>>> Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
('a', 5)
>>> a,b = Counter(c for c in mystr.lower() if c in "aeiou").most_common(1)[0]
>>> a
'a'
>>> b
5
>>>
Upvotes: 4
Reputation: 1
Substring through the sentence string, and increment an array of integers indexed 0-4 (for a-u) at the end find the maximum value of the array and have it print the correct statement
Upvotes: -2
Reputation: 251041
Use collections.Counter
:
>>> from collections import Counter
>>> c = Counter()
>>> vowels = {'a', 'e', 'i', 'o', 'u'}
for x in 'aaaeeeeeefffddd':
if x.lower() in vowels:
c[x.lower()] += 1
...
>>> c
Counter({'e': 6, 'a': 3})
>>> letter, count = c.most_common()[0]
>>> letter, count
('e', 6)
Upvotes: 2