从本质上来说,我是python(和一般编码)的新手,我试图根据我作为第一个项目之前编写的密码制作一个简单的转换器/加密器。我对密码的想法是,使用4个单独的交替密码翻译字符串中的每个字符,然后将其组合为最终产品。我已经想出了如何使用1 maketrans(table)将字符串转换为某种东西。但我不知道如何使最终产品由4个交替的翻译表组成。
#My desired table
string = "aabbccdd"
dict1 = {"a":"1," , "b":"2," , "c":"3," , "d":"4,"}
dict2 = {"a":"5," , "b":"6," , "c":"7," , "d":"8,"}
dict3 = {"a":"9," , "b":"10," , "c":"11," , "d":"12,"}
dict4 = {"a":"13," , "b":"14," , "c":"15," , "d":"16,"}
table1 = string.maketrans(dict1)
table2 = string.maketrans(dict2)
table3 = string.maketrans(dict3)
table3 = string.maketrans(dict4)
#The desired result would be "aabbccdd"->"1,5,10,14,3,7,12,16"
#My existing single table
submission = input()
dict1 = {"a":"41","b":"22","c":"13","d":"43"}
table1 = submission.maketrans(dict1)
print(submission.translate(table1))
我的预期结果和实际结果在代码块中可见。我想我对编码还太陌生,甚至无法开始思考如何做到这一点,所以我希望有人可以向我解释如何做到。甚至没有直接要求解决方案,但是如果有人可以告诉我从哪里开始,那将会有很多帮助。
答案 0 :(得分:0)
如果我了解您的输出示例的模式,我建议您使用循环迭代器:
from itertools import cycle
string = "aabbccdd"
dict1 = {"a":"1," , "b":"2," , "c":"3," , "d":"4,"}
dict2 = {"a":"5," , "b":"6," , "c":"7," , "d":"8,"}
dict3 = {"a":"9," , "b":"10," , "c":"11," , "d":"12,"}
dict4 = {"a":"13," , "b":"14," , "c":"15," , "d":"16,"}
dicts = cycle([dict1, dict2, dict3, dict4])
encrypted_str = ""
for i in string:
dict = next(dicts) #iterates sequentially over the dictionaries
encrypted_str += dict[i] #encrypt the letter using random dict and add
print(encrypted_str[:-1]) #[:-1] to remove the last ","
输出:1,5,10,14,3,7,12,16
我可能会感兴趣的是为您的加密添加一些随机性。 (要解密,您需要确保字典顺序的安全性) 我建议编写自己的翻译器功能。 这是我能想到的一个例子:
import random
string = "aabbccdd"
dict1 = {"a":"1," , "b":"2," , "c":"3," , "d":"4,"}
dict2 = {"a":"5," , "b":"6," , "c":"7," , "d":"8,"}
dict3 = {"a":"9," , "b":"10," , "c":"11," , "d":"12,"}
dict4 = {"a":"13," , "b":"14," , "c":"15," , "d":"16,"}
dicts = [dict1, dict2, dict3, dict4]
encrypted_str = ""
for i in string:
dict = dicts[random.randint(0,3)] #each iteration choose randomly a new dictionary
encrypted_str += dict[i] #encrypt the letter using random dict and add to the encrypted string
print(encrypted_str[:-1]) #[:-1] to remove the last ","
输出示例为:13,5,2,6,7,3,12,12
答案 1 :(得分:0)
如果不需要使用string.maketrans
和str.translate
,则可以使用一个字典,其中'a'
,'b'
,'c'
和{{1} }是键,值是具有相应数字的列表,因此'd'
的值将是'a'
,['1', '5', '9', '13']
的值将是'b'
,依此类推,该['2', '6', '10', '14']
可以使用字典理解来构建,至于翻译,您可以使用dict
,enumerate
和模(str.join
)运算符:
%
输出:
alpha = "abcd"
n = len(alpha)
d = {c : [str(j) for j in range(i, n * n + 1, n)] for i, c in enumerate(alpha, 1)}
string = "aabbccdd"
def encrypt(s):
return ','.join(d[c][i % n] for i, c in enumerate(s))
encrypted = encrypt(string)
print(encrypted)
该方法适用于任何字母,只要要加密的字符串使用该字母生成的语言即可。