【问题标题】:Caesar Cipher - Wrong Output凯撒密码 - 错误的输出
【发布时间】:2015-04-14 04:18:32
【问题描述】:

问题是:

您的程序需要解码一个名为 “加密的.txt”。编写它的人使用了指定的密码 “key.txt”。此密钥文件类似于以下内容:

A    B
B    C
C    D
D    E
E    F
F    G
G    H
H    I
I    J
J    K
K    L
L    M
M    N
N    O
O    P
P    Q
Q    R
R    S
S    T
T    U
U    V
V    W
W    X
X    Y
Y    Z
Z    A

左栏代表明文字母,右栏 表示对应的密文。

您的程序应使用“key.txt”解码“encrypted.txt”文件 并将明文写入“decrypted.txt”。

我有:

decrypt = ""
keyfile = open("key.txt", "r")
cipher = {}

for keyline in keyfile:
    cipher[keyline.split()[0]] = keyline.split()[1]
keyfile.close()
encrypt = []
encryptedfile = open("encrypted.txt", "r")
readlines = encryptedfile.readlines()
str = ""

for line in readlines:
    str = line
    letter = list(str)
    for i in range(len(letter)):
        if letter[i]==",":
            decrypt += ","
        elif letter[i] == ".":
            decrypt+= "."
        elif letter[i] == "!":
            decrypt += "!"
        elif letter[i] == " ":
            decrypt += " "
        else:
            found = False
            count = 0

while (found == False):
    if (letter[i] == keyline.split()[0][count]):
        decrypt += keyline.split()[1][count]
        found = True
        count += 1
        print decrypt

encryptedfile.close()
decryptedfile = open("decrypted.txt", "w")
decryptedfile.write(decrypt)
decryptedfile.close()

这是 Python 语言。输出确实生成了一个名为decrypted.txt 的文件,但文件中唯一的内容是A,这对我来说没有意义。对于问题它应该输出更多的权利?

【问题讨论】:

  • 欢迎来到*,您能否更具体地说明您的问题是什么,您的程序是如何失败的?另外,我们需要知道您使用的是什么语言,您可以编辑您的问题以添加 tat 信息吗?
  • 如果这确实是你的代码,那么缩进级别给它的语义与你可能想要的明显不同......事实上,在任何只包含标点符号或空格的文件中,你会得到一个NameError,因为你有一个代码路径,你可以在其中进入你的while (found == False)循环,而found从未被定义......即使缩进固定,情况仍然可能如此。

标签: python encryption caesar-cipher


【解决方案1】:

使用key.txt中给出的密钥解密文件enrcypted.txt并将结果保存到decrypted.txt

with open('key.txt', 'r') as keyfile:                                           
    pairs = [line.split() for line in keyfile]                                  
    columns = [''.join(x) for x in zip(*pairs)]                                 
    # Or to make it work with lower case letters as well:                       
    # columns = [''.join(x)+''.join(x).lower() for x in zip(*pairs)]            
    key = str.maketrans(                                                        
            *reversed(columns)                                                  
            )                                                                   

with open('encrypted.txt', 'r') as encrypted_file:                              
    decrypted = [line.translate(key) for line in encrypted_file]                

with open('decrypted.txt', 'w') as decrypted_file:
    decrypted_file.writelines(decrypted) 

【讨论】:

    【解决方案2】:

    您的 while 块应缩进 3 次。
    除了 count += 1 应该比它的邻居少一个块

    while 块的内部根本没有使用 keyline 是字典这一事实。

    【讨论】:

      最近更新 更多