繁体   English   中英

在Python中计算字符串中的元音数量

[英]Counting number of vowels in a string in 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):
  return len ([c for c in st if c.lower() in 'aeiou'])

肯定有更好的方法。 这是一个

   def countvowels(s):
      s = s.lower()
      return sum(s.count(v) for v in "aeiou")

您可以使用列表理解来做到这一点

def countvowels(w):
    vowels= "aAiIeEoOuU"
    return len([i for i in list(w) if i in list(vowels)])

您可以使用正则表达式模式轻松完成此操作。 但是在我看来,您想要不这样做。 所以这是一些代码:

string = "This is a test for vowel counting"
print [(i,string.count(i)) for i in list("AaEeIiOoUu")]

您可以通过多种方式进行操作,请先在Google中查看,然后再进行询问,我已复制了其中的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)

您还可以尝试使用来自collections Counter (仅适用于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)

暂无
暂无

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

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