我程序的解密部分不起作用

2024-09-27 07:21:32 发布

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

我目前正在写一个程序,加密和解密文本和.txt文件,整个程序工作正常,除了部分解密.txt文件。这是程序中该部分的代码。你知道吗

while True:
    message = int(input('Open file (1) or type message (2)? '))
    if message == 1:
        file = input('What file should be opened? ')
        file = file + '.txt'
        with open(file) as file:
            file = [line.rstrip('\n') for line in file]
        break
    elif message == 2:
        file = input('What was the encrypted message? ')
        break
    else:
        print('Please enter 1 or 2\n')

displacement = int(input('What was the displacement? '))

for i in range(len(file)):
    num = ord(file[i])
    num -= displacement
    letter = chr(num)
    new_message.append(letter)
new_message = ''.join(new_message)
print('\n' + new_message)

我得到的错误是:“TypeError:ord()需要一个字符,但找到了长度为5的字符串”。同一段代码用于加密文本,为什么会有不同,又有什么问题?你知道吗


Tags: or文件代码文本程序txtmessagenew
1条回答
网友
1楼 · 发布于 2024-09-27 07:21:32

嗯,代码有很多问题。 首先,这是凯撒密码吗?如果是这样,您应该指定是否在UI中加密/解密文本,因为您必须这样做:

if encrypted==False: num -= displacement
else: num+=displacement 

其次,我发现对于密码,使用不同的for循环来处理文本更容易,比如:

for char in text:
    do_stuff
    print char 
    ## etc

最后,主要问题是如何读取文本文件。你在列清单。你应该试着做:

file = file.read()

相关问题 更多 >

    热门问题