计算一个句子中的特定元音

时间:2013-11-01 20:30:59

标签: python

我发现了一些这样的例子,但我的问题略有不同。

我需要扫描像

这样的句子
For letter in sentence
if letter == "a" or letter == "A": letterATotal = letterATotal + 1
elif letter == "e" or letter == "E": letterETotal = letterETotal + 1

等一直到U. 但是我需要将它们全部进行比较并打印包含最频繁的行 “最常见的元音是A发生5次”。 问题是我不知道如何显示实际的字母。我只能显示号码。 有什么想法吗?

4 个答案:

答案 0 :(得分:4)

看看这个:

>>> 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'
>>>

以下是collections.Counter的参考资料。


修改

以下是对正在发生的事情的逐步演示:

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

答案 1 :(得分:2)

使用collections.Counter

>>> from collections import Counter
>>> c = Counter()
>>> vowels = {'a', 'e', 'i', 'o', 'u'}
for x in 'aaaeeeeeefffddd':
    if x.lower() in vowels:
        c[x.lower()] += 1
...         
>>> c
Counter({'e': 6, 'a': 3})
>>> letter, count = c.most_common()[0]
>>> letter, count
('e', 6)

答案 2 :(得分:0)

如果您使用的是Python 3或更高版本,则以下代码可以使用:

s = input ('Enter a word or sentence to find how many vowels:')

sub1 = 'a'
sub2 = 'e'
sub3 = 'i'
sub4 = 'o'
sub5 = 'u'

print ('The word you entered: ', s)

print ('The count for a: ', s.count(sub1))

print ('The count for e: ', s.count(sub2))

print ('The count for i: ', s.count(sub3))

print ('The count for o: ', s.count(sub4))

print ('The count for u: ', s.count(sub5))

答案 3 :(得分:-2)

通过句子字符串子串,并递增一个索引为0-4的整数数组(对于a -u) 最后找到数组的最大值并让它打印正确的语句