0

这是我的任务:

编写一个程序,从键盘读取文本直到“!” 被发现。

使用由字母“A”到“Z”下标的整数数组,计算每个字母出现的次数(无论是大写还是小写)。在单独的计数器中,还计算“其他”字符的总数。

打印出找到的每个字母的计数。此外,打印非字母字符的计数。

通过检查数组,打印出元音的数量和辅音的数量。

这是我的代码:

msg = input("What is your message? ")

print ()

num_alpha = 26
int_array = [0] * num_alpha
vowel = [0] * 10000
consanant = [0] * 10000

for alpha in range(num_alpha):
    int_array[alpha] = chr(alpha + 65)
    if int_array[alpha] == 'A' or int_array[alpha] == 'E' or int_array[alpha] == 'I' or int_array[alpha] == 'O' or int_array[alpha] == 'U':
        vowel[alpha] = int_array[alpha]
        print(vowel[alpha])
    else:
        consanant[alpha] = int_array[alpha]



print()

lett = 0
otherch = 0
num_vowels = 0
num_consanants = 0

count_character = [0] * 100000

length = len(msg)

for character in msg.upper():
    if character == "!":
        otherch = otherch + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        break
    elif character < "A" or character > "Z":
        otherch = otherch + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
    else:
        lett = lett + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        if vowel[(alpha)] == (character):
            num_vowels = num_vowels + 1
            print(vowel[alpha])
        else:
            num_consanants = num_consanants + 1

print("Number of Letters =", lett)
print("Number of Other Characters = ", otherch)
print("Number of Vowels = ", num_vowels)
print("Number of Consanants = ", num_consanants)


for character in msg.upper():
        print("Character", character, "appeared" , count_character[ord(character)] , "time(s).")
        if character == "!":
            break

每次我输入一个字符串时,它都无法识别元音。如果我输入“abe!” 它会打印:

Number of Letters = 3 
Number of Other Characters =  1 
Number of Vowels=  0 
Number of Consanants =  3 
Character A appeared 1 time(s). 
Character B appeared 1 time(s). 
Character E appeared 1 time(s).
Character ! appeared 1 time(s).
4

2 回答 2

2
if vowel[(alpha)] == (character):
  num_vowels = num_vowels + 1
  print(vowel[alpha])

在此代码中,您的 alpha 超出范围,这意味着 alpha 将是前一个 for 循环的最后一次迭代中的任何内容

另外我会推荐一种更好的方法来检查元音使用in

vowels = ['a','e','i','o','u']
char = 'a'
if char in vowels:
  pass              # you have found a vowel
于 2013-08-15T00:19:52.197 回答
0

在这里你需要分配alpha. 否则,它将for在顶部取循环的最后一个值(因此它将是 25)。

else:
    lett = lett + 1
    count_character[ord(character)] = count_character[ord(character)] + 1
    alpha = ord(character) - ord('A') # <-- need this
    if vowel[(alpha)] == (character):
        num_vowels = num_vowels + 1
        print(vowel[alpha])
    else:
        num_consanants = num_consanants + 1
于 2013-08-15T00:22:14.573 回答