2016-03-21 99 views
-6
vowels = 'aeiou' 
ip_str = input("Enter a string: ") 
ip_str = ip_str.casefold() 
count = {}.fromkeys('aeiouAEIOU',0) 
for char in ip_str: 
    if char in count: 
     count[char] += 1 

print(count) 

如何在Python中編寫程序來接受字符串並計算其中的元音數目?計算字符串中的元音

+0

代碼片段與您的「問題」有什麼關係? – Sayse

回答

0

您已經計算每個元音的代碼。如果你想知道元音的總數,然後只需運行總計保持如下:

ip_str = input("Enter a string: ") 
ip_str = ip_str.casefold() 
count = {}.fromkeys('aeiou',0) 
total = 0 

for char in ip_str: 
    if char in count: 
     count[char] += 1 
     total += 1 

print(count) 
print("Number of vowels:", total) 

例如:

Enter a string: Hello THERE 
{'a': 0, 'o': 1, 'u': 0, 'i': 0, 'e': 3} 
Number of vowels: 4 

如果你想讓它單獨計算大寫和小寫:

ip_str = input("Enter a string: ") 
count = {}.fromkeys('aeiouAEIOU', 0) 
total = 0 

for char in ip_str: 
    if char in count: 
     count[char] += 1 
     total += 1 

print(count) 
print("Number of vowels:", total) 

給你:

Enter a string: Hello THERE 
{'i': 0, 'O': 0, 'e': 1, 'U': 0, 'o': 1, 'E': 2, 'a': 0, 'I': 0, 'A': 0, 'u': 0} 
Number of vowels: 4 
2

可以使用sum()功能:如果你想找到根據關你的字典的計數

vowels = "aeiou" 
number = sum(1 for char in ip_str if char.lower() in vowels) 

,這樣做:

number = sum(count.values())