2017-04-11 3 views
-2

Ich habe eine Zuweisung über Strings in Schleife und ich muss herausfinden, wie viele (a, e, ich, o, u) in der Eingabe. Ich habe es getan, aber ich denke, es ist zu lang. Ich möchte es kürzer machen, aber ich habe keine Ahnung wie.Wie kann ich es kürzer und besser machen?

Dies ist mein Code:

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") 
+1

Sollen wir _guess_, dass dies ... Python? – deceze

+0

Ja, es ist Python, sorry hat nicht erwähnt, dass – abdulraman

+2

Mögliche Duplikate von [Wie Vokale und Konsonanten in Python zählen?] (Http://stackoverflow.com/questions/43164161/how-to-count-vowels-and-consonants -in-Python) – BWMustang13

Antwort

0

Einfacher Ansatz nach this question:

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") 
0

Statt 5 Variablen zum Zählen und 5 Konstante zum Vergleich des Wörterbuch verwenden:

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

oder - schöner -

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

so Ihr vollständiger Code lautet

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)) 
1

Sie können nur Ihre Liste von Zeichen definieren Sie (Vokale) Pflege in einem String, dann dictionary comprehension verwenden. Dieser Code wird gedruckt, was Sie wollen, und lassen Sie auch mit allen in einem Wörterbuch gespeicherten Werte genannt 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")