凯撒密码和处理非字母字符

2024-04-29 01:56:06 发布

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

我正在尝试在Python2.7中实现Caesar cipher,但遇到了逗号、冒号等字符的问题。问题是我想在文本加密后保持不变,但由于某些原因,“encrypt_-plantext”函数会输出不带空格或任何非字母符号的字符数。我尝试过串联,但没有成功;与“.join”方法相同。 如有任何建议,我将不胜感激。在

import sys


plain = open('plain.txt')
try:
    plaintext = plain.read()
finally:
    plain.close()


decrypt = open('decrypt.txt')
try:
    decrypttext = decrypt.read()
finally:
    decrypt.close()


crypto = open('crypto.txt')
try:
    cryptotext = crypto.read()
finally:
    crypto.close()


key = open('key.txt')
try:
    keytext = key.read()
finally:
    key.close()


for cezarkey in keytext[0]:
    print cezarkey


def encrypt_plaintext(x):
    crypt = ''
    for i in x:
        if i>='a' and i<='z' or i>='A' and i<='Z':
            crypt += chr(ord(i)+int(cezarkey)%26)
        else:
            i+(crypt)

    print "The decrypted message is: " + crypt
    #crypto = open('crypto.txt', 'w')
    #crypto.write(crypt)
    #crypto.close()

#szyfr = [ chr(ord(c)+k%26) if c>='a' and c<='z' or c>='A' and c<='Z' else c for c in tekst ]
#print ''.join(szyfr)


def decrypt_cyphertext(x):
    crypt = ""
    for i in x:
        crypt += chr((((ord(i) - 97) - int(cezarkey)) % 26) + 97)
    print "The decrypted message is: " + crypt
    decrypt = open('decrypt.txt', 'w')
    decrypt.write(crypt)
    decrypt.close()


if sys.argv[1:3] == ['-c', '-e']:
    encrypt_plaintext(plaintext)

elif sys.argv[1:3] == ['-c','-d']:
    decrypt_cyphertext(cryptotext)

Tags: keyintxtforclosereadopencrypto