-2

我有一个关于循环中字符串的分配,我需要找出输入中有多少 (a,e,i,o,u) 。我已经完成了,但我认为它太长了。我想让它更短,但我不知道怎么做。

这是我的代码:

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:")

a=len(x)

x1=0

x2=0

x3=0

x4=0

x5=0

for i in range(a):
    h=ord(x[i])

    if h == 105:
        x1+=1
    elif h == 111: 
        x2+=1
    elif h == 97:
        x3+=1
    elif h == 117:
        x4+=1
    elif h == 101:
        x5+=1

print("There were",x3,"'a's")
print("There were",x5,"'e's")
print("There were",x1,"'i's")
print("There were",x2,"'o's")
print("There were",x4,"'u's")
4

3 回答 3

1

您可以在字符串中定义您关心的字符列表(元音),然后使用字典理解。此代码将打印出您想要的内容,并为您提供存储在名为的字典中的所有值vowel_count

vowels = 'aeiou'

x=input("enter the taxt that you need me to count how many (a,e,i,o,u) in it:")

vowel_count = {vowel: x.count(vowel) for vowel in vowels}

for vowel in vowels:
    print("There were ",vowel_count[vowel]," '", vowel, " 's")
于 2017-04-11T14:06:16.483 回答
0

使用字典代替5用于计数的变量和用于比较的常量:5

h = {105: 0, 111: 0, 97: 0, 117: 0, 101: 0}

或者 - 更好 -

h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0}

所以你的完整代码将是

x = input("Enter the text that you need me to count how many (a,e,i,o,u) in it: ")
h = {'i': 0, 'o': 0, 'a': 0, 'u': 0, 'e': 0}

for i in x:              # there is no need to index characters in the string
    if i in h:
      h[i] += 1

for char in h: 
    print("There were {} '{}'s".format(h[char], char))  
于 2017-04-11T14:00:31.203 回答
0

根据这个问题的简单方法:

x = input("Enter the text that you need me to count how many (a,e,i,o,u) are in it:")

print("There were", x.count('a'), "'a's")
print("There were", x.count('e'), "'e's")
print("There were", x.count('i'), "'i's")
print("There were", x.count('o'), "'o's")
print("There were", x.count('u'), "'u's")
于 2017-04-11T14:02:44.783 回答