0

所以这是我的代码,它使用计数器来跟踪句子中元音的数量。虽然我看不出有什么问题,但如果你运行它并输入一个句子,它总是会输出说我是最多的。即使您不添加 I。任何人都可以看到我哪里出错了吗?

from collections import Counter
vowelCounter = Counter()
vowelList = {'a','e','i','o','u'}
userString = input("Enter a string ")
displayed = False
vowelCounter = Counter(a=0,e=0,i=0,o=0,u=0)
for letter in userString:
    letter = letter.lower()
    if letter in vowelList:
        vowelCounter[letter] +=1

print(vowelCounter) #just to check the actual amount of vowels confirms the rest of the code

for vowelCount1 in list(vowelCounter.items())[0:1]:
    char, count = vowelCount1
    for vowelCount2 in list(vowelCounter.items())[1:2]:
        char2, count2 = vowelCount2
        if count2 == count:
            for vowelCount3 in list(vowelCounter.items())[2:3]:
                char3, count3 = vowelCount3
                if count3 == count:
                    for vowelCount4 in list(vowelCounter.items())[3:4]:
                        char4, count4 = vowelCount4
                        if count4 == count:
                            for vowelCount5 in list(vowelCounter.items())[4:5]:
                                char5, count5 = vowelCount5
                                if count5 == count:
                                    print("{0},{1},{2},{3} and {4} are all equal, occuring {5} times each".format(char,char2,char3,char4, char5, count))
                                    break
                                else:
                                    print("{0},{1},{2} and {3} are all equal, occuring {4} times each".format(char,char2,char3,char4, count))
                                    break
                        else:
                            print("{0},{1} and {2} are all equal, occuring {3} times each".format(char,char2,char3, count))
                            break
                else:
                    print("{0} and {1} are all equal, occuring {2} times each".format(char,char2, count))
                    break
        else:
            print("{0} occured the most with {1}".format(char, count))
            break
    break   
4

1 回答 1

0

据我所知,这有效

import operator
vowelList = ['a','e','i','o','u']
userString = input("Enter a string ")
displayed = False
vowelCounter = {'a':0, 'e': 0, 'i':0, 'o':0, 'u':0}
for letter in userString:
    letter = letter.lower()
    if letter in vowelList:
        vowelCounter[letter] +=1

print(vowelCounter) #just to check the actual amount of vowels confirms the rest of the code

maxKey = max(vowelCounter.iteritems(), key=operator.itemgetter(1))[0]
print('Max value is {0} with {1}'.format(maxKey, vowelCounter[maxKey]))
于 2013-11-13T17:26:28.163 回答