2016-10-24 28 views
2

私はPythonには新しく、私自身のCaesar暗号解読器を作ることに決めました。私はencrypterを作りましたが、それは問題ありません。しかし、decrypterは1つの単語だけを正しく復号することができます。私が文章を入力すると、それは解読をすべて一緒にマージします。これは簡単に修正できますか?Python Caesar暗号解読

def decrypt(): 
    ciphertext = raw_input('Please enter your Encrypted sentence here:') 
    shift = input('Please enter its shift value: ') 
    space = [] 

    cipher_ords = [ord(x) for x in ciphertext] 
    plaintext_ords = [o - shift for o in cipher_ords] 
    plaintext_chars = [chr(i) for i in plaintext_ords] 
    plaintext = ''.join(plaintext_chars) 
    print 'Decryption Successful' 
    print "" 
    print 'Your encrypted sentence is:', plaintext 

decrypt() 
+1

暗号化プログラムで問題が発生していないことを確認してください。 – usr2564301

+0

あなたのコードはここで大丈夫です。あなたは入力と期待される出力を提供できますか? –

+0

また、任意のコードを実行できるように 'input'を使用しないでください。代わりに 'int(raw_input())'を実行してください。 –

答えて

1

私が提案しているのは、すべてのスペースであなたのraw_input()を分割し、分割入力の各単語を繰り返してから、その文をスペースで戻し合うことです。私が考えることができる最も標準的な解決策になるようだ:

def decrypt(): 
    ciphertext = raw_input('Please enter your Encrypted sentence here:') 
    shift = int(raw_input('Please enter its shift value: ')) 
    space = [] 

    # creat a list of encrypted words. 
    ciphertext = ciphertext.split() 

    # creat a list to hold decrypted words. 
    sentence = [] 

    for word in ciphertext: 
     cipher_ords = [ord(x) for x in word] 
     plaintext_ords = [o - shift for o in cipher_ords] 
     plaintext_chars = [chr(i) for i in plaintext_ords] 
     plaintext = ''.join(plaintext_chars) 
     sentence.append(plaintext) 

    # join each word in the sentence list back together by a space. 
    sentence = ' '.join(sentence) 
    print 'Decryption Successful\n' 
    print 'Your encrypted sentence is:', sentence 

decrypt() 

出力:

Please enter your Encrypted sentence here: lipps xlivi 
Please enter its shift value: 4 
Decryption Successful 

Your encrypted sentence is: hello there 

注:

  • はちょうどそれためのPython 2.xでinput()を行うことはありません暗黙的にeval()を使用しています。これは非常に危険です。代わりにint(raw_input())を使用してください。
  • 新しい行を作成する余分なprintステートメントを削除しました。代わりに2番目のprint文に新しい行を追加してください。
0

"hello there"に関するご意見を入力したところ、この問題は印刷できないアスキー文字と関係していると思われます。あなたはシーザーのサイファーの2つの重要な部分を欠いています。

最初の問題について、考えてみます。

>>> chr(ord(' ') - 4) 
'\x1c' 

をああ!スペースの左側に4文字(32)は... ASCIIファイルの区切り文字です!どのようにシーザーはの粘土のタブレットに収めましたか?第二の問題については

>>> chr(ord('A') - 4) 
'=' 

「A」は、真のシーザーサイファーにラップアラウンド必要がありますが、その代わりに、あなたは(まあ、そうでもない)非アルファベットASCIIコードの後背地を模索しています。

  1. はシーザーCYPHERから非アルファベット文字を除外:

    あなたはこのように、2つの重要なステップを含める必要があります。

  2. 最後に近づくと文字が折り返されるようにしてください。A - 1Zに等しくなければなりません。
+0

どうすればいいですか? –

0

あなたは、おそらくそれはを暗号化されていないあなたの「暗号化」のテキストのようにspace文字を解読するためにないたかったです。このような場合は、ここにコードの変更一部です:

cipher_ords  = [ord(x) if x != " " else -1 for x in ciphertext] 
plaintext_ords = [o - shift if o != -1 else -1 for o in cipher_ords] 
plaintext_chars = [chr(i) if i != -1 else " " for i in plaintext_ords] 

は(あまりにも、cipher_ordsplaintext_ords内の各スペースのシンボルとconsequenltyため-1を持ってみましょうplaintext_charsではこの-1が元spaceシンボルに戻ります。 。)

関連する問題