Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python(2.7)中使Caesar解码器循环?_Python_List_Python 2.7_Encryption_Decoder - Fatal编程技术网

如何在Python(2.7)中使Caesar解码器循环?

如何在Python(2.7)中使Caesar解码器循环?,python,list,python-2.7,encryption,decoder,Python,List,Python 2.7,Encryption,Decoder,在经历了许多挫折之后,我制作了我的第一个凯撒解码器: 但现在的问题是让程序循环 例如,如果我们想把doge移1,没问题,它是ephf 但是xyz呢,移位是4 所以编程专业人士会帮助第一次的新手,也就是新手:p 谢谢 import string def main(): inString = raw_input("Please enter the word to be " "translated: ") key = i

在经历了许多挫折之后,我制作了我的第一个凯撒解码器:

但现在的问题是让程序循环

例如,如果我们想把doge移1,没问题,它是ephf

但是xyz呢,移位是4

所以编程专业人士会帮助第一次的新手,也就是新手:p 谢谢

import string
def main():        
    inString = raw_input("Please enter the word to be "
                         "translated: ")
    key = int(raw_input("What is the key value? "))

    toConv = [ord(i) for i in inString] #now want to shift it by key
    toConv = [x+key for x in toConv]
    #^can use map(lambda x:x+key, toConv)
    result = ''.join(chr(i) for i in toConv)

    print "This is the final result due to the shift", result
只需将键添加到所有实际字符代码,然后如果添加的值大于z,则与字符代码z进行模运算,并与字符代码a进行相加


一般来说,要对某些内容进行包装,您可以使用Python中的模函数%以及要包装的数字和范围。例如,如果我想打印数字1到10次,我会:

i = 0
while 1:
    print(i%10+1)
    # I want to see 1-10, and i=10 will give me 0 (10%10==0), so i%10+1!
    i += 1
在这种情况下,这会有点困难,因为您使用的是ord,它没有一个很好的值范围。如果你做了类似string.ascii_小写的事情,你可以

import string
codex = string.ascii_lowercase

inString = "abcdxyz"
key = 3
outString = [codex[(codex.index(char)+key)%len(codex)] for char in inString]
然而,由于您使用ord,我们从ord'A'==65到ord'z'==122,因此范围为0->57,例如范围58,常数为65。换言之:

codex = "ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz"
# every char for chr(65) -> chr(122)

codex = ''.join([chr(i+65) for i in range(58)]) # this is the same thing!
我们可以这样做,但它将包含字符[\]^_`

inString, key = 'abcxyzABCXYZ', 4
toConv = [(ord(i)+key-65)%58 for i in inString]
result = ''.join(chr(i+65) for i in toConv)
print(result)
# "efgBCDEFG\\]^"
我建议使用

因此,我们可以做到以下几点:

key = 1
table = string.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[key:] + string.ascii_lowercase[:key] + string.ascii_uppercase[key:] + string.ascii_uppercase[:key])
然后我们可以使用它如下:

'doge'.translate(table) # Outputs 'ephf'
'Doge'.translate(table) # Outputs 'Ephf'
'xyz'.translate(table)  # Outputs 'yza'
特别是,这不会更改非ascii小写或大写字符(如数字或空格)的字符

'3 2 1 a'.translate(table) # Outputs '3 2 1 b'

下面是我编写的易于理解的Python代码。而且,我认为经典的凯撒密码没有定义如何使用标点符号;我认为经典的秘密信息是不定时的,只包含信件。我写这篇文章只是为了处理经典的罗马字母表,并且不改变传递任何其他字符

作为奖励,您可以使用这个移位为13的代码来解码ROT13编码的笑话

def caesar_ch(ch, shift):
    """
    Caesar cipher for one character.  Only shifts 'a' through 'z'
    and 'A' through 'Z'; leaves other chars unchanged.
    """
    n = ord(ch)
    if ord('a') <= n <= ord('z'):
        n = n - ord('a')
        n = (n + shift) % 26
        n = n + ord('a')
        return chr(n)
    elif ord('A') <= n <= ord('Z'):
        n = n - ord('A')
        n = (n + shift) % 26
        n = n + ord('A')
        return chr(n)
    else:
        return ch

def caesar(s, shift):
    """
    Caesar cipher for a string.  Only shifts 'a' through 'z'
    and 'A' through 'Z'; leaves other chars unchanged.
    """
    return ''.join(caesar_ch(ch, shift) for ch in s)

if __name__ == "__main__":
    assert caesar("doge", 1) == "ephf"

    assert caesar("xyz", 4) == "bcd"

    assert caesar("Veni, vidi, vici.", 13) == "Irav, ivqv, ivpv."
最后的部分是代码的自检。如果您将其作为独立程序运行,它将测试自身,并在测试失败时断言


如果您对这段代码有任何疑问,请提问,我会解释。

我知道这是一个老话题,但我今天碰巧正在研究它。我发现这条线索中的答案很有用,但它们似乎都使用了循环的决策。我想出了一种方法来实现同样的目标,只需使用modulesRestrients操作符%。这允许数字保持在表的范围内并循环。它还允许轻松解码

# advCeaser.py
# This program uses a ceaser cypher to encode and decode messages
import string

def main():
    # Create a table to reference all upper, lower case, numbers and common punctuation.
    table = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz1234567890,.!?-@'

    print 'This program accepts a message and a key to encode the message.'
    print 'If the encoded message is entered with the negative value of the key'
    print 'The message will be decoded!'

    # Create accumulator to collect coded message 
code =''

    # Get input from user: Message and encode key
    message = raw_input('Enter the message you would like to have encoded:')
    key = input('Enter the encode or decode key: ')

    # Loop through each character in the message
    for ch in message:
        # Find the index of the char in the table add the key value
        # Then use the remainder function to stay within range of the table.
        index = ((table.find(ch)+key)%len(table))

        # Add a new character to the code using the index
        code = code + table[index]

    # Print out the final code
    print code

main()
编码和解码输出如下所示

编码:

This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:The zephyr blows from the east to the west!
Enter the encode or decode key: 10
croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
解码:

This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
Enter the encode or decode key: -10
The zephyr blows from the east to the west!
对不起,如果我的格式看起来像猫咪,我昨天真的发现了stackoverflow!是的,我的字面意思是:

相关:
This program accepts a message and a key to encode the message.
If the encoded message is entered with the negative value of the key
The message will be decoded!
Enter the message you would like to have encoded:croj0ozr92jlvy73jp2ywj4rojok34j4yj4roj7o34G
Enter the encode or decode key: -10
The zephyr blows from the east to the west!