计算句子中特定的元音

2024-04-25 21:36:13 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我需要扫描一个句子

For letter in sentence
if letter == "a" or letter == "A": letterATotal = letterATotal + 1
elif letter == "e" or letter == "E": letterETotal = letterETotal + 1

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


Tags: orinforifso字母sentence例子
3条回答

如果使用的是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))

看看这个:

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

这里是^{}的参考。在


编辑:

下面是一个逐步演示的过程:

^{pr2}$

使用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)

相关问题 更多 >

    热门问题