计数元音的数量在一个字符串在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缩进,有用)。
有没有更好的方法来做到这一点?使用for循环?
我会做类似
def countvowels(st):
return len ([c for c in st if c.lower() in 'aeiou'])
+1以避免“count”。 – 2014-10-28 04:46:57
'sum(c.lower()in'aeiou'for c in st)'保存临时列表 – 2014-10-28 05:02:45
你可以做,使用列表理解
def countvowels(w):
vowels= "aAiIeEoOuU"
return len([i for i in list(w) if i in list(vowels)])
您不需要'list'构造函数。字符串在Python中是可迭代的。 – 2014-10-28 04:46:22
这是真的! +1 – user3378649 2014-10-28 04:48:02
肯定有更好的方法。这是一个。
def countvowels(s):
s = s.lower()
return sum(s.count(v) for v in "aeiou")
你可以使用正则表达式很容易地做到这一点。但是在我看来,你希望不这样做。因此,这里是一些代码,这样做的:
string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]
可以以不同的方式,在谷歌先看看前问这样做,我就复制粘贴其中2
def countvowels(string):
num_vowels=0
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
data = raw_input("Please type a sentence: ")
vowels = "aeiou"
for v in vowels:
print v, data.lower().count(v)
您也可以尝试Counter
从collections
(仅适用于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)
这里是一个版本使用地图:
phrase=list("This is a test for vowel counting")
base="AaEeIiOoUu"
def c(b):
print b+":",phrase.count(b)
map(c,base)
还看到:http://stackoverflow.com/questions/19237791/counting-vowels-in-python – Paul 2014-10-28 05:15:32
这个问题似乎会偏离因为它是关于改善工作代码 – 2014-10-28 15:29:22