gpt4 book ai didi

python - 如何输出最常见的元音

转载 作者:太空宇宙 更新时间:2023-11-03 11:26:02 27 4
gpt4 key购买 nike

我已经设法编写了这个代码:

def vowels(s) :
result = 0
n = 0
while n<len(s):
if s[n] in "AEIOUaeiou" : result = result+1
n = n+1
return result

line = input("Type a line of text: ")
print("The line contains", vowels(line), "vowels")

这让我知道总共有多少个元音字母排成一行。但我想知道如何更改它以便输出出现次数最多的元音及其出现次数

最佳答案

您可以使用 collections.Counter获取文本中每个元音的出现次数。

>>> from collections import Counter

>>> def vowels(s):
... return Counter(c for c in s if c in "AEIOUaeiou")

>>> counter = vowels("Lorem ipsum lorem")
>>> print counter
Counter({'e': 2, 'o': 2, 'i': 1, 'u': 1})
>>> print sum(counter.values())
6
>>> print counter.most_common()
[('e', 2), ('o', 2), ('i', 1), ('u', 1)]

关于python - 如何输出最常见的元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33603938/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com