for n in range(0, len(plaintext)):
if plaintext[n] == ' ':
new = ord(plaintext[n])
else:
new = ord(plaintext[n]) + ord(key[n%len(key)]) - 65
if new > 90:
所以我想知道如何确保所有标点符号都没有加密,只有字母加密?我知道这不是加密的好方法,但它适用于学校项目,所以如果有人可以帮助我会很棒。此外,当我解密它没有正确解密,有时忘记完全停止和东西我该如何解决这个问题?感谢。
答案 0 :(得分:3)
定义所有标点符号;
punctuation = " ',.;:.!?\r\n"
替换
的所有实例if plaintext[n] == ' ':
通过
if plaintext[n] in punctuation:
<强>加成强>
虽然您的代码功能正常,但它并没有使用Python提供的许多强大工具。让我来说明一下。使用列表推导可以像这样完成加密/解密(带有从文本中删除的标点符号);
In [42]: plaintext = 'THISISAPLAINTEXT' # Your algorithm only works for capitals.
In [43]: key = 'SPAMEGGS'
In [44]: count = int(len(plaintext)/len(key))+1
In [45]: stretchedkey = [ord(c) for c in key*count]
In [46]: # Encryption
In [47]: plainnum = [ord(c) for c in plaintext]
In [48]: ciphernum = [a+b-65 for a, b in zip(plainnum, stretchedkey)]
In [49]: ciphertext = ''.join([chr(c) if c <= 90 else chr(c-26) for c in ciphernum])
In [50]: ciphertext
Out[50]: 'LWIEMYGHDPIZXKDL'
In [51]: # Decryption
In [52]: ciphernum = [ord(c) for c in ciphertext]
In [53]: decryptnum = [a-b+65 for a, b in zip(ciphernum, stretchedkey)]
In [54]: decrypt = ''.join([chr(c) if c >= 65 else chr(c+26) for c in decryptnum])
In [55]: decrypt
Out[55]: 'THISISAPLAINTEXT'
一些解释。
列表推导可以将字符串转换为一个字符串的列表;
In [69]: [c for c in 'THISISATEXT']
Out[69]: ['T', 'H', 'I', 'S', 'I', 'S', 'A', 'T', 'E', 'X', 'T']
或字符值列表;
In [70]: [ord(c) for c in 'THISISATEXT']
Out[70]: [84, 72, 73, 83, 73, 83, 65, 84, 69, 88, 84]
您甚至可以在执行此操作时删除标点符号。
In [80]: [c for c in 'THIS IS A TEXT.' if c not in ' .']
Out[80]: ['T', 'H', 'I', 'S', 'I', 'S', 'A', 'T', 'E', 'X', 'T']
zip
内置允许您迭代列表组合;
In [73]: p = [ord(c) for c in 'THISISATEXT']
In [74]: q = [ord(c) for c in 'SPAMEGGSSPAMEGGS']
In [77]: p
Out[77]: [84, 72, 73, 83, 73, 83, 65, 84, 69, 88, 84]
In [78]: q
Out[78]: [83, 80, 65, 77, 69, 71, 71, 83, 83, 80, 65, 77, 69, 71, 71, 83]
In [79]: [a+b for a, b in zip(p, q)]
Out[79]: [167, 152, 138, 160, 142, 154, 136, 167, 152, 168, 149]
提示:
列出字符串中所有标点符号及其索引。
In [82]: [(n, c) for n, c in enumerate('THIS IS A TEXT.') if c in ' .']
Out[82]: [(4, ' '), (7, ' '), (9, ' '), (14, '.')]