Count the amount of vowels in a sentence and displ

2019-07-15 23:21发布

问题:

This is my code so far for counting vowels. I need to to scan through a sentence, count and compare the vowels and then display the top occurring vowels.

from collections import Counter
vowelCounter = Counter()
sentence=input("sentence")
for word in sentence:
    vowelCounter[word] += 1
vowel, vowelCount= Counter(vowel for vowel in sentence.lower() if vowel in "aeiou").most_common(1)[0]

Does anyone have a better way to do this ?

回答1:

IMO, long lines are best avoided for the sake of clarity:

#!/usr/local/cpython-3.3/bin/python

import collections

sentence = input("sentence").lower()
vowels = (c for c in sentence if c in "aeiou")
counter = collections.Counter(vowels)
most_common = counter.most_common(1)[0]
print(most_common)


回答2:

If all you are after is the max-occurrent vowel, you don't really need Counter.

counts = {i:0 for i in 'aeiou'}
for char in input("sentence: ").lower():
  if char in counts:
    counts[char] += 1
print(max(counts, key=counts.__getitem__))