2

到目前为止,这是我计算元音的代码。我需要扫描一个句子,计算和比较元音,然后显示出现频率最高的元音。

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]

有没有人有更好的方法来做到这一点?

4

2 回答 2

2

IMO,为了清楚起见,最好避免使用长线:

#!/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)
于 2013-11-12T16:15:19.953 回答
1

如果您所追求的只是 max-occurrent 元音,那么您实际上并不需要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__))
于 2013-11-12T16:09:54.487 回答