如何使用数组计算输入中的元音和辅音?

2024-10-02 00:40:01 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的任务:

Write a program which reads in text from the keyboard until '!' is found.

Using an array of integers subscripted by the letters 'A' through 'Z', count the number occurrences of each letter (regardless of whether it is upper or lower case). In a separate counter, also count the total number of "other" characters.

Print out the count for each letter found. Also, print the count of the non-letter characters.

By inspecting the array, print out the count of the number of vowels, and the number of consonants.

这是我的密码:

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!”它将打印:

^{pr2}$

Tags: oroftheinalphacountarraynum
2条回答
if vowel[(alpha)] == (character):
  num_vowels = num_vowels + 1
  print(vowel[alpha])

在这段代码中,alpha超出了范围,这意味着alpha将是上一个for循环的最后一次迭代的内容

另外,我建议使用in来检查元音

^{pr2}$

这里您需要分配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

相关问题 更多 >

    热门问题