在Python中计算字符串中元音的数量
好吧,我所做的就是在Python中计算字符串中元音的数量,python,Python,好吧,我所做的就是 def countvowels(st): result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U") return result 这是可行的(我知道这篇文章中的缩进可能是错误的,但我在python中缩进的方式是可行的) 有更好的
def countvowels(st):
result=st.count("a")+st.count("A")+st.count("e")+st.count("E")+st.count("i")+st.count("I")+st.count("o")+st.count("O")+st.count("u")+st.count("U")
return result
这是可行的(我知道这篇文章中的缩进可能是错误的,但我在python中缩进的方式是可行的)
有更好的方法吗?使用for循环?我会这样做
def countvowels(st):
return len ([c for c in st if c.lower() in 'aeiou'])
您可以使用列表理解来实现这一点
def countvowels(w):
vowels= "aAiIeEoOuU"
return len([i for i in list(w) if i in list(vowels)])
肯定有更好的办法。这里有一个
def countvowels(s):
s = s.lower()
return sum(s.count(v) for v in "aeiou")
您可以使用regex模式轻松地实现这一点。但在我看来,你不想这样做。下面是一些代码:
string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]
你可以用不同的方式来做,在问之前先在谷歌上看看,我已经复制粘贴了其中的两个
def countvowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
您还可以尝试使用
集合中的计数器(仅适用于Python 2.7+),如下所示。它将显示每个字母重复了多少次
from collections import Counter
st = raw_input("Enter the string")
print Counter(st)
但是你想要特别的元音然后试试这个
import re
def count_vowels(string):
vowels = re.findall('[aeiou]', string, re.IGNORECASE)
return len(vowels)
st = input("Enter a string:")
print count_vowels(st)
以下是使用map的版本:
phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
print b+":",phrase.count(b)
map(c,base)
您不需要列表
构造函数。字符串在python中是可编辑的。sum(对于st中的c,在'aeiou'中为c.lower())
保存创建临时列表另请参见:这个问题似乎与主题无关,因为它是关于改进工作代码的
phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
print b+":",phrase.count(b)
map(c,base)