Count the amount of vowels in a sentence and display the most frequent

北城余情 提交于 2019-12-11 02:46:51

问题


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__))


来源:https://stackoverflow.com/questions/19933875/count-the-amount-of-vowels-in-a-sentence-and-display-the-most-frequent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!