简体   繁体   English

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

[英]Counting number of vowels in a string in Python

Okay so what I did was 好吧,所以我做了

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

This works(I'm aware indentation might be wrong in this post, but the way I have it indented in python, it works). 这有效(我知道缩进在这篇文章中可能是错误的,但是我在python中缩进的方式有效)。

Is there a better way to do this? 有一个更好的方法吗? Using for loops? 使用循环?

I would do something like 我会做类似的事情

def countvowels(st):
  return len ([c for c in st if c.lower() in 'aeiou'])

There's definitely better ways. 肯定有更好的方法。 Here's one. 这是一个

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

You can do that using list comprehension 您可以使用列表理解来做到这一点

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

You could use regex pattern to do this easily. 您可以使用正则表达式模式轻松完成此操作。 But it looks to me, that you want to do it without. 但是在我看来,您想要不这样做。 So here is some code to do so: 所以这是一些代码:

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

you can do it in various ways, first look in google before asking, i had copy pasted 2 of them 您可以通过多种方式进行操作,请先在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)

You can also try Counter from collections (only available from Python 2.7+) as shown below . 您还可以尝试使用来自collections Counter (仅适用于Python 2.7+),如下所示。 It'll show how many times each letter has been repeated. 它会显示每个字母重复了多少次。

from collections import Counter
st = raw_input("Enter the string")
print Counter(st)

But you want vowels specifically then try this. 但是,您需要专门的元音,然后尝试一下。

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)

Here is a version using map: 这是使用地图的版本:

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