我设法编写了这个代码:
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")
这给了我总共有多少个元音符号.. 但我想知道如何更改它以便输出 最常发生的元音和发生的次数
答案 0 :(得分:1)
您可以使用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)]
答案 1 :(得分:1)
使用collections.Counter
及其most_common
方法
from collections import Counter
def vowels(s) :
vow_found = [i for i in s.lower() if i in 'aeiou']
c = Counter(vow_found)
return len(vow_found), c.most_common()
line = input("Type a line of text: ")
numvow, most_com = vowels(line)
print("The line contains", numvow, "vowels")
print("and the most common are", most_com)
,输入
hello I am your friend today
产生
The line contains 10 vowels
and the most common are [('o', 3), ('i', 2), ('a', 2), ('e', 2), ('u', 1)]
答案 2 :(得分:0)
您可以使用collections.Counter
执行此操作:
import collections
vowels = lambda s: collections.Counter(i for i in s if i in 'AEIOUaeiou').most_common(1)[0]
line = input("Type a line of text: ")
v = vowels(line)
print("The most frequently vowel is", v[0], 'the times is', v[1])
答案 3 :(得分:0)
我的做法是什么:
lower()
将输入设为小写。希望这会有所帮助:
line = input("Type a line of text: ").lower()
print(sorted([(i,line.count(i)) for i in "aeiou"], key=lambda x:x[1], reverse=True)[0])
答案 4 :(得分:0)
def vowels(s) :
vowel_letters = "AEIOUaeiou"
result = []
for vowel in vowel_letters:
result.append((vowel,s.count(vowel)))
result.sort(key=lambda tup: tup[1])
return result[-1]
line = raw_input("Type a line of text: ")
print vowels(line)
答案 5 :(得分:0)
相同
的更简单的简单代码from collections import Counter
def most_common_vowel(input_string):
return Counter(
filter(lambda x: x in "aeiou", input_string.lower())
).most_common(1)
使用filter
函数从字符串中删除非元音,并使用Counter
获取最常用的元素