Python 函数,该函数将字符串作为输入,并计算元音在字符串中出现的次数
因此,我对python非常陌生,正在学习基础知识。我试图创建一个函数,该函数计算字符串中元音的数量,并返回每个元音在字符串中出现的次数。例如,如果我给它这个输入,它就会打印出来Python 函数,该函数将字符串作为输入,并计算元音在字符串中出现的次数,python,Python,因此,我对python非常陌生,正在学习基础知识。我试图创建一个函数,该函数计算字符串中元音的数量,并返回每个元音在字符串中出现的次数。例如,如果我给它这个输入,它就会打印出来 >>>countVowels('Le Tour de France') a, e, i, o, and u appear, respectively, 1,3,0,1,1 times. 我创建了这个helper函数,但是我不确定如何使用它 def find_vowels(sent
>>>countVowels('Le Tour de France')
a, e, i, o, and u appear, respectively, 1,3,0,1,1 times.
我创建了这个helper函数,但是我不确定如何使用它
def find_vowels(sentence):
count = 0
vowels = "aeiuoAEIOU"
for letter in sentence:
if letter in vowels:
count += 1
print count
然后我想也许我可以使用格式将它们放在写入位置,但我不确定将使用的符号,例如,函数的一行可以是:
'a, , i, o, and u appear, respectively, {(count1)}, {(count2)}, {(count3)}, {(count4)}, {(count5)} times'
我不确定如何才能在函数中满足上述要求。您需要使用字典来存储值,因为如果直接添加计数,您将丢失有关正在计数的元音的确切信息
def countVowels(s):
s = s.lower() #so you don't have to worry about upper and lower cases
vowels = 'aeiou'
return {vowel:s.count(vowel) for vowel in vowels} #a bit inefficient, but easy to understand
另一种方法是:
def countVowels(s):
s = s.lower()
vowels = {'a':0,'e':0,'i':0,'o':0,'u':0}
for char in s:
if char in vowels:
vowels[char]+=1
return vowels
要打印此文件,请执行以下操作:
def printResults(result_dict):
print "a, e, i, o, u, appear, respectively, {a},{e},{i},{o},{u} times".format(**result_dict)
一个更简单的答案是使用Counter类
def count_vowels(s):
from collections import Counter
#Creates a Counter c, holding the number of occurrences of each letter
c = Counter(s.lower())
#Returns a dictionary holding the counts of each vowel
return {vowel:c[vowel] for vowel in 'aeiou'}
这也行得通。不知道它的效率是高还是低。它为每个aeiou列出了一个列表,并对其进行了汇总嗯,我记得这个例子来自我刚才上的一节课,如果这本书是由Perkovic博士写的,我也知道这是一个家庭作业问题(要正确格式化),诚然,这会更容易,但似乎两者都违反了作业的目的(如果是字典赋值和循环)而且占用的空间比需要的要多。简单性带来的好处远远超过了尺寸的边际增长。最大的可能是127,除非你进入unicode,在这种情况下你是对的。我一直认为,学习手动操作是很好的,只要你知道正确的/规范的/明智的方法。其中一个伟大的方法是python的另一个特点是几乎不必使用循环。学习用类似C的方式编写python就像拿着螺丝刀用拇指转动螺丝一样毫无意义。
a =input("Enter string: ")
vowels = sum([a.lower().count(i) for i in "aeiou"])
print(vowels)