How to get the most common vowel

I managed to do this:

def vowels(s) :
    result = 0
    n = 0
    while n<len(s):
        if s[n] in "AEIOUaeiou" : result = result+1
        n = n+1
    return result

line = input("Type a line of text: ")
print("The line contains", vowels(line), "vowels")

which gives me the number of vowels in general. But I want to know how to change it so that it gives out the vowels (s) that met most often and how many times it happened

+4
source share
6 answers

You can use collections.Counterto get the number of occurrences of each vowel in the text.

>>> from collections import Counter

>>> def vowels(s):
...     return Counter(c for c in s if c in "AEIOUaeiou")

>>> counter = vowels("Lorem ipsum lorem")
>>> print counter
Counter({'e': 2, 'o': 2, 'i': 1, 'u': 1})
>>> print sum(counter.values())
6
>>> print counter.most_common()
[('e', 2), ('o', 2), ('i', 1), ('u', 1)]
+1
source

Use collections.Counterand its methodmost_common

from collections import Counter

def vowels(s) :
    vow_found = [i for i in s.lower() if i in 'aeiou']
    c = Counter(vow_found)
    return len(vow_found), c.most_common()

line = input("Type a line of text: ")
numvow, most_com = vowels(line)
print("The line contains", numvow, "vowels")
print("and the most common are", most_com)

which with the entrance

hello I am your friend today

produces

The line contains 10 vowels
and the most common are [('o', 3), ('i', 2), ('a', 2), ('e', 2), ('u', 1)]
+1
source

collections.Counter, :

import collections

vowels = lambda s: collections.Counter(i for i in s if i in 'AEIOUaeiou').most_common(1)[0]

line = input("Type a line of text: ")
v = vowels(line)

print("The most frequently vowel is", v[0], 'the times is', v[1])
0

:

  • lower() .
  • .
  • , .
  • .

Hope this helps:

line = input("Type a line of text: ").lower()
print(sorted([(i,line.count(i)) for i in "aeiou"], key=lambda x:x[1], reverse=True)[0])
0
source
def vowels(s) :
    vowel_letters = "AEIOUaeiou"
    result = []
    for vowel in vowel_letters:
        result.append((vowel,s.count(vowel)))
    result.sort(key=lambda tup: tup[1])
    return result[-1]

line = raw_input("Type a line of text: ")
print vowels(line)
0
source

Shorter simpler code for the same

from collections import Counter
def most_common_vowel(input_string):
    return Counter(
            filter(lambda x: x in "aeiou", input_string.lower())
        ).most_common(1)

Use the function filterto remove unspoken strings from a string and use Counterto get the most common item

0
source

Source: https://habr.com/ru/post/1615003/


All Articles