1

这是我的程序:

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

print ()

num_alpha = 26
int_array = [0] * num_alpha

for alpha in range(num_alpha):
    int_array[alpha] = chr(alpha + 65)
    print(int_array[alpha], end = "")

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 == "!":
        print("lett =", lett)
        print("other char = ", otherch)
        print("num_vowels = ", num_vowels)
        print("num_consanants = ", num_consanants)
    elif character < "A" or letter > "Z":
        otherch = otherch + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        print(count_character[ord(character)])
    else:
        lett = lett + 1
        count_character[ord(character)] = count_character[ord(character)] + 1
        print(count_character[ord(character)])

for character in msg:
        print("character", character, "appeared" , count_character[ord(character)] , "times")

我打算列出有关消息的各种功能(每个字母出现的次数、元音的数量、非字母字符的数量等),但每次我打印最后一个打印语句时,它都指出每个字符出现 0次。有帮手吗?

编辑:我已经想通了-

因为之前的循环,而不是:

for character in msg:
    print("character", character, "appeared" , count_character[ord(character)] , "times")

代码必须是:

for character in msg.upper():
    print("character", character, "appeared" , count_character[ord(character)] , "times")
4

1 回答 1

0

我认为或至少一个问题是,如果您使用 input() 而不是 raw_input() 则需要小心

方法 input() 被认为是未保存的,而 raw_input 真正读入一个字符串/字符

>>> input()
a
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 1, in <module>
NameError: name 'a' is not defined
>>> raw_input()
a
'a'
>>>

另请注意:

>>> input()
"hello my name is tom"
'hello my name is tom'
>>> raw_input()
"hello my name is tom"
'"hello my name is tom"'
>>>

raw_input() 始终将输入识别为字符串,而您必须输入引号才能让 input() 知道您要输入字符串

于 2013-08-14T13:38:25.437 回答