1

所以目前,我的代码看起来像这样(感谢我在另一篇文章中提供的帮助)

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")

for character in phrase: 
     #Loops through phrase and shows ascii numbers, example: hello is: 104,101,108,108,111
    x = ord(character)

     #adds a shift to each character so if shift is 1 'hello' becomes: ifmmp 105,102,109,109,112
    result += chr(x + shift)


print "\n",result,"\n"

问题是,如果我输入多个单词,例如: hello world ,移位为 1

输出是:ifmmp!xpsme

感叹号显示为空格(因班次而异)。我正在考虑做一个 if 语句来检测空格:

phrase = raw_input("Enter text to Cipher: ")
shift = int(raw_input("Please enter shift: "))
result = ("Encrypted text is: ")

for character in phrase: 
        #Loops through phrase and shows ascii numbers, example: hello is: 104,101,108,108,111
    x = ord(character)

    if x == ord(' '):
        print "\nfound a space space"

        #adds 1 to each character so 'hello' becomes: ifmmp 105,102,109,109,112
    result += chr(x + shift)


print "\n",result,"\n"

但我不知道如何将空格添加到结果变量中。另外,我在这个线程中看到:Caesar's Cipher using python, can use a little help

JeffB 使用 while 循环来处理 ASCII 表 32 是空格,127 是 DEL。他为什么用96?我不明白。

while x < 32:
    x += 96

while x > 127:
    x -= 96

抱歉这个问题比较长。提前谢谢了!你的帮助对我来说是无价的。

4

4 回答 4

3

您可以跳过空格:

for character in phrase:
    x = ord(character)

    if character == ' ':
        result += ' '
    else:
        result += chr(x + shift)

您的班次不会将输出限制为 ASCII。如果要确保这一点,则应使用模运算符:

chr(32 + (x + shift) % (127 - 32))
于 2013-08-03T10:05:41.510 回答
1

您可以像这样添加空格:

if character.isspace():
   result += ' '

或在空格处拆分字符串:

例子:

>>> "hello world".split()
['hello', 'world']

代码:

new_strs = []
result = ("Encrypted text is:")

for word in phrase.split(): 
    new_word = []
    for character in word:
       x = ord(character) + shift
       new_word.append(chr(x if 97 <= x <= 122 else 96 + x % 122))

    new_strs.append("".join(new_word))

print result, " ".join(new_strs)

为什么x if 97 <= x <= 122 else 96 + x % 122

因为'z'shift = 1x + shift将是 123,即'{'.所以,'a'而不是'{'用 122( ) 取新法令值的模数ord('z')并将 96( ord('a') -1) 添加到它。

输出:

$ python so.py
Enter text to Cipher: hello xyz
Please enter shift: 1
Encrypted text is: ifmmp yza
于 2013-08-03T10:06:07.450 回答
0

只需使用基本上为您加密或解密消息的 maketrans 和翻译功能。它们为问题提供了一个非常简短和有效的解决方案

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)

然后你不必担心添加空格或任何东西,这是一个完全工作的凯撒密码加密程序

于 2015-06-23T18:12:48.830 回答
0

空格不是 Cesar Cipher(又名 Shift Cipher)需要处理的唯一问题。从历史上看,字符设置为全部大写(或小写),所有空格和所有标点符号都被删除。

这个站点展示了一个很好的 Cesar Cipher Implementation 示例,它处理所有标点符号的删除以及密钥生成(可选)。链接的实现选择使用由正则表达式实现的允许字符的白名单。

# Message is a the string to be encrypted / decrypted
sub(r'[^A-Z]', '', message.upper())
于 2015-10-19T15:46:55.373 回答