如何确保所有标点未加密?

如何确保所有标点未加密?

问题描述:

 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

最好把它分成2个问题。第一个可能与正则表达式 –

定义所有标点符号;

punctuation = " ',.;:.!?\r\n" 

通过

if plaintext[n] in punctuation: 

加成

更换

if plaintext[n] == ' ': 

所有情况下,当你的代码是功能性的,它不使用大量的强大的工具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 built-in允许您迭代列表组合;

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, '.')] 
+0

它仍然不起作用 – Shoaib

+0

这是不是很丰富。你可以编辑你的问题,并添加一个示例输入/输出? –

+0

我如何让它不做撇号(')? – Shoaib