2014-10-29 149 views
-1

我對我手動輸入的字符串的計數有點困惑。我基本上是在計算沒有空格的字數和字符數。另外如果可能的話,誰可以幫助計算元音?計算一個字符串python

這是我到目前爲止有:

vowels = [ 'a','e','i','o','u','A','E','I','O','U'] 
constants= ['b','c','d','f','g','h','j','k','l','m','n','p','q','r','s','t','v','w','x','y','z'] 

s= input ('Enter a Sentence: ') 

print ('Your sentence is:', s) 

print ('Number of Characters', len(s)); 

print ('Number of Vowels', s); 
+0

這有助於http://stackoverflow.com/questions/20226110 /檢測元音-vs-consonants-in-python – neiesc 2014-10-29 23:32:21

回答

2
s = input("Enter a sentence: ") 

word_count = len(s.split()) # count the words with split 
char_count = len(s.replace(' ', '')) # count the chars having replaced spaces with '' 
vowel_count = sum(1 for c in s if c.lower() in ['a','e','i','o','u']) # sum 1 for each vowel 

更多信息:

str.splithttp://www.tutorialspoint.com/python/string_split.htm

sum

sum(sequence[, start]) -> value 

Return the sum of a sequence of numbers (NOT strings) plus the value 
of parameter 'start' (which defaults to 0). When the sequence is 
empty, return start. 

str.replacehttp://www.tutorialspoint.com/python/string_replace.htm

+0

非常感謝。這是我需要的。 – 2014-10-29 23:41:55

+0

如果這個解決方案解決了你的問題,請考慮接受它作爲正式答案(票號旁邊的勾號) – Totem 2014-10-29 23:48:02

0
vowels = [ 'a','e','i','o','u'] 
sentence = "Our World is a better place" 
count_vow = 0 
count_con = 0 
for x in sentence: 
    if x.isalpha(): 
     if x.lower() in vowels: 
      count_vow += 1 
     else: 
      count_con += 1 
print count_vow,count_con 
+0

你有一個類型的行8,應該是'count_vow' + = 1 – Hamatti 2014-10-29 23:37:45

+0

啊對不起,這是一個打字錯誤 – Hackaholic 2014-10-29 23:40:25

0

元音:

這樣做的基本方法是使用一個for循環和檢查每個字符,如果他們在一個字符串,列表或其他序列(在這個元音存在案件)。我認爲這是你應該首先學習的方式,因爲它對初學者來說是最容易理解的。

def how_many_vowels(text): 
    vowels = 'aeiou' 
    vowel_count = 0 
    for char in text: 
    if char.lower() in vowels: 
     vowel_count += 1 
    return vowel_count 

一旦你瞭解並找出list comprehensions,你可以做到這一點

def how_many_vowels(text): 
    vowels = 'aeiou' 
    vowels_in_text = [ch for ch in text if ch.lower() in vowels] 
    return len(vowels_in_text) 

或@totem寫道,使用金額

def how_many_vowels(text): 
    vowels = 'aeiou' 
    vowel_count = sum(1 for ch in text if ch.lower() in vowels) 
    return vowel_count