2016-03-21 65 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())