正在尝试解密.txt文件

2024-06-07 18:16:19 发布

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

所以我试着用一个.txt文件在我的程序中运行它,这个文件有ROT13加密,但它不会把它打印出来解密。例如,我希望它能够输入一个文件名,比如test.txt,其中包含加密的消息,然后解密并打印出来。这是我尝试过的,我需要知道的,以便改进它。在这段代码中,我还得到了一个语法错误TypeError:ord()需要一个字符,但找到了长度为4的字符串。我真的很想帮忙

    print("You selected Decrytion for Rot Cipher")
    typeofD = input("What type of Encrytion did you encrpt with, R for Rot and B for Bit Shift")
    if typeofD == 'R':
        coded = input("Enter the Test file text :")
        filecontents = open(coded,'r')
        file1 = filecontents .readlines()
        message = file1
        key = 13
        decryp_text = ""
    for i in range(len(message)):
        temp = ord(message[i]) - key
        if ord(message[i]) == 32:
            decryp_text += " "
        elif temp < 65:
            temp += 26
            decryp_text += chr(temp)
        else:
            decryp_text += chr(temp)

print("Decrypted Text: {}".format(decryp_text))

Tags: 文件texttxtmessageforinputiftemp
2条回答

您是否需要以这种方式执行该功能,或者只是尝试执行rot13?因为您可以使用buildincodec函数,该函数具有rot13转换方法:

>>> import codecs
>>> inputText = "Hello World!"
>>> codecs.encode(inputText, 'rot_13')
'Uryyb Jbeyq!'
>>> outputText = codecs.encode(inputText, 'rot_13')
>>> codecs.encode(outputText, 'rot_13')
'Hello World!'

(取决于您使用的python版本)str/stringmaketrans函数,该函数允许您为每个字符设置1对1的相关性:

>>> rot13 = str.maketrans('ABCDEFGHIJKLMabcdefghijklmNOPQRSTUVWXYZnopqrstuvwxyz', 'NOPQRSTUVWXYZnopqrstuvwxyzABCDEFGHIJKLMabcdefghijklm')
>>> str.translate(inputText, rot13)
'Uryyb Jbeyq!'
>>> str.translate(outputText, rot13)
'Hello World!'
  • 否则—

我建议手动进行旋转,因为使用一种圆形数组方法和模运算会更容易:

>>> alphaList
['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
>>> def rot13(inputText):
...   global alphaList
...   output = []
...   for letter in inputText:
...     ascii = ord(letter)
...     if (ascii == 32):
...       output.append(' ')
...     else:
...       transLetter = alphaList[(alphaList.index(letter.upper()) + 13 ) % 26]
...     if (ascii >= 97 and ascii <= 122):
...       transLetter = transLetter.lower()
...     output.append(transLetter)
...   output = ''.join(output)
...   return(output)

>>> msg = rot13('Hello World')
>>> msg
'Uryyb bJbeyq'


最后一个我没有考虑特殊字符或任何东西,但逻辑现在应该是显而易见的。让我知道这是否有帮助

你有点倒退了。我已经修改了你的一些代码以正确工作。具体而言temp = ord(message[i]) - key改为temp = ord(message[i]) + keyelif temp < 65改为elif temp > 122temp += 26改为temp -= 26

for i in range(len(message)):
    temp = ord(message[i]) + key
    if ord(message[i]) == 32:
        decryp_text += " "
    elif temp > 122:
        temp -= 26
        decryp_text += chr(temp)
    else:
        decryp_text += chr(temp)

相关问题 更多 >

    热门问题