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?
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
>>>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments