【问题标题】:Encrypting a text file but leaving the space in?加密文本文件但保留空间?
【发布时间】:2015-06-23 17:42:30
【问题描述】:

我已经成功地创建了一个代码,该代码使用程序前面的随机生成的偏移因子来加密文本文件,但我不知道如何在不加密的情况下将空格留在原处?

text_file = open("sample.txt", "r")

characters = []
for line in text_file:
    for c in line:
        characters.append(c)

text_ascii = []
text_number = 0
new_number = 0
cipher_text = ""
for i in characters:
    if i not in (" "):
        text_ascii = ord(i)
        text_number = text_ascii + offset_factor
        if text_number > 126:
            text_number = text_number - 94
        new_number = chr(text_number)
        cipher_text = cipher_text + new_number

print (cipher_text)

我现在的代码根本不加密空格或包含它们。

文本文件的内容(称为“sample.txt”,全部在一行上)是:

在拉曼恰的某个地方,在一个我不想记住名字的地方,不久前住着一位绅士,他在架子上放着长矛和古老的盾牌,养着一只瘦马和一只赛狗.

【问题讨论】:

  • 如果我不在 (" "): => 如果我 != " ":

标签: python encryption spaces


【解决方案1】:

你忘了处理它一个空格的情况。

if ...:
   ...
else:
  cipher_text += ' '

【讨论】:

    【解决方案2】:

    这会起作用,但我建议你使用函数 maketrans 和翻译,在 python 3+ 中你必须使用 str.maketrans 和 str.translate,但是 python 2.x 你必须导入字符串并使用 string.maketrans和字符串。翻译。使用这些函数,python 可以提供一种非常高效、简短且易于遵循的凯撒密码加密方法...

    message = input('enter message').lower()
    offset = int(input('enter offset (enter a negative number to decrypt)'))
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    enc_alphabet = (alphabet[alphabet.index(alphabet[offset]):len(alphabet)])+alphabet[0:offset]
    data = str.maketrans(alphabet,enc_alphabet)
    final_message = str.translate(message, data)
    print(final_message)
    

    【讨论】:

      猜你喜欢
      • 2018-12-27
      • 1970-01-01
      • 2017-10-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-14
      • 1970-01-01
      相关资源
      最近更新 更多