简体   繁体   English

字符串python 3中最常见的元音

[英]Most frequent vowel in string python 3

I have created the program for the most frequent vowel in a string but the problem that i am having is i want to print only one letter for the most frequent vowel, not both. 我已经为字符串中最频繁的元音创建了程序,但是我遇到的问题是我只想为最频繁的元音仅打印一个字母,而不能同时打印两个字母。 My code is displayed below: 我的代码显示在下面:

from collections import Counter
words = input("Enter a line of text: ")
vowel = "aeiouAEIOU"
x = Counter(c for c in words.upper() if c in vowel)

most = {k: x[k] for k in x if x[k] == max(x.values())}

for i in most:
    vowel = i
    y = most[i]
    print("The most occuring vowel is:",vowel, "with",y,"occurences")

if vowel != words:
    print("No vowels found in user input")

When i run the code for example i enter "aa ee" it will print: 例如,当我运行代码时,我输入“ aa ee”,它将打印:

The most occuring vowel is: A with 2 occurences
The most occuring vowel is: E with 2 occurrences

I only want it to print either A or E? 我只希望它打印A或E?

Why you don't simply use Counter.most_common() which is most appropriate way for doing this job? 为什么您不简单地使用Counter.most_common()来完成这项工作呢?

words = input("Enter a line of text: ")
vowels = set("aeiouAEIOU")
x = Counter(c for c in words if c in vowels)

print x.most_common()

Also note that you don't need to use word.upper since you have all the vowels type.And as said in comment you can use set for preserving the vowels which its membership checking complexity is O(1). 另外请注意,由于您具有所有的元音类型,因此不需要使用word.upper ,并且如注释中所述,您可以使用set来保留其成员资格检查复杂度为O(1)的元音。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM