Python 3-键错误0

2024-09-29 21:24:48 发布

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

在代码中运行encode()时出现以下错误。

Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
  encode()
File "/home/kian/dummyphone-app/python/encode.py", line 31, in encode
  varb.insert(pl + 1, number2letter[randint(0, 26)])
KeyError: 0

代码是:

from collections import defaultdict
from random import randint

def encode():
number2letter = {1 : 'a', 2 : 'b', 3 : 'c', 4 : 'd', 5 : 'e', 6 : 'f', 7 : 'g',
8 : 'h', 9 : 'i', 10 : 'j', 11 : 'k', 12 : 'l', 13 : 'm', 14 : 'n', 15 : 'o', 16 : 'p', 17 : 'q',
18 : 'r', 19 : 's', 20 : 't', 21 : 'u', 22 : 'v', 23 : 'w', 24 : 'x', 25 : 'y', 26 : 'z'}

encode = {"a": "y", "b": "z", "c": "a", "d": "b", "e": "c", "f": "d", "g": "e",
"h": "f", "i": "g", "j": "h", "k": "i", "l": "j", "m": "k", "n": "l", "o": "m", 
"p": "n", "q": "o", "r": "p", "s": "q", "t": "r", "u": "s", "v": "t", "w": "u", 
"x": "v", "y": "w", "z": "x"}
print("This is a work in progress.")
var = input("Please input the phrase to be encoded, and then press Enter. ")
vara = list(var.lower())
i = 0
while i < len(var):
    if (vara[i] in encode) :
        vara[i] = encode[vara[i]]
        i += 1
    else:
        vara[i] = vara[i]
        i += 1
pl = 0
dummyx = 0
dummyx2 = 0
varb = vara
for i in vara:
    pl = pl + 1
    if (dummyx == 1):
        varb.insert(pl + 1, number2letter[randint(0, 26)])
        pl = pl + 1
        if (dummyx2 == 0):
            dummyx2 = 1
        if (dummyx2 == 1):
            varb.insert(pl + 1, number2letter[randint(0, 26)])
            dummyx2 = 0
            pl = pl + 1
        dummyx = 0
    else:
        dummyx = 1
print(''.join(varb))

我试着让它在特定的位置随机添加字母,在模式中:

普通字母,随机字母,普通字母,随机字母,随机字母

每5个字母重复一次。 剩下的代码应该在“encode”字典中将字母编码成一个代码。 忽略数字和符号。我也有一个解码器,如果你想看的话,我也可以把它贴在这里。


Tags: 代码inifvar字母encodefilepl
3条回答

randint(0, 26)可以返回0,并且number2letter中没有键0

把它改成randint(1, 26)

在Python 3中生成随机小写字母的另一种方法是random.choice(string.ascii_lowercase)(不要忘记import string)。

randint(0, 26)在其可能的输出中同时包含026。您的number2letter指令没有用于数字0的字母。要解决这个问题,需要将参数调整为randint

完全按照错误消息,number2letter没有键0的值。您需要将呼叫更改为randint

number2letter[randint(1, 26)]

来自the documentation

random.randint(a, b)

Return a random integer N such that a <= N <= b.

相关问题 更多 >

    热门问题