这是我的任务:
编写一个程序,从键盘读取文本,直到'!'找到了。
使用由'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).
答案 0 :(得分: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
答案 1 :(得分: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