简体   繁体   English

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

[英]The decryption part of my program doesn't work

I am currently writing a program that encrypts and decrypts text and .txt files, The entire program works fine except for the part that decrypts .txt files. 我目前正在编写一个用于加密和解密文本和.txt文件的程序,除了解密.txt文件的那一部分之外,整个程序都可以正常工作。 Here is the code for that section of the program. 这是程序该部分的代码。

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)

The error I'm getting is: 'TypeError: ord() expected a character, but string of length 5 found'. 我得到的错误是:'TypeError:ord()需要一个字符,但是找到了长度为5的字符串'。 The same piece of code works for encrypting text, why is this different and what is wrong? 相同的代码段可用于加密文本,这为何不同,又有什么问题呢?

Well there is a lot of things wrong with the code. 好的,代码有很多问题。 First off, is this a Ceaser Cipher? 首先,这是Ceaser密码吗? If so you should specify if the text is being encrypted/decrypted in the UI cause you would have to do this: 如果是这样,您应该指定是否在用户界面中对文本进行加密/解密,因为您必须这样做:

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

Second, I found for ciphers it's easier to do a different for loop to handle the text like: 其次,我发现对于密码而言,执行不同的for循环来处理类似文本的内容更容易:

for char in text:
    do_stuff
    print char 
    ## etc

Finally, the main problem is how you are reading the text file. 最后,主要问题是如何阅读文本文件。 You are making a list. 您正在制作清单。 You should try doing: 您应该尝试做:

file = file.read()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM