在我的代码中运行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个字母。 其余的代码应该在“编码”字典中将字母编码为代码。 数字和符号被忽略。我也有一个解码器,如果你想看到它我也可以在这里发布。
答案 0 :(得分:6)
randint(0, 26)
可以返回0
,0
中没有关键number2letter
。
将其更改为randint(1, 26)
。
在Python 3中生成随机小写字母的另一种方法是random.choice(string.ascii_lowercase)
(不要忘记import string
)。
答案 1 :(得分:1)
randint(0, 26)
在其可能的输出中包含0
和26
。您的number2letter
字典没有0
号的字母。要解决此问题,您需要将参数调整为randint
。
答案 2 :(得分:1)
正如错误消息所示,number2letter
没有密钥0
的值。您需要将来电更改为randint
:
number2letter[randint(1, 26)]
random.randint(a, b)
返回一个随机整数
N
,使a <= N <= b
。