在Python中使用计数器和列表?

时间:2013-08-14 13:26:29

标签: python arrays list character counter

这是我的计划:

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")

1 个答案:

答案 0 :(得分:0)

我认为或者至少有一个问题是,如果使用input()而不是raw_input()

,则需要小心

方法input()被认为是unsave,而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()知道您要输入字符串