簡體   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