2016-08-01 145 views
0

我在嘗試替換文件中的字符時遇到了問題。腳本替換文件中的字符

#!/usr/bin/env python 

with open("crypto.txt","r") as arquivo: 
    data = arquivo.read() 
for caracter in data: 
    if "a" in data: 
     data = data.replace("a","c") 
    elif "b" in data: 
     data = data.replace("b","d") 
    elif "c" in data: 
     data = data.replace("c","e") 
    elif "d" in data: 
     data = data.replace("d","f") 
    elif "e" in data: 
     data = data.replace("e","g") 
    elif "f" in data: 
     data = data.replace("f","h") 
    elif "g" in data: 
     data = data.replace("g","i") 
    elif "h" in data: 
     data = data.replace("h","j") 
    elif "i" in data: 
     data = data.replace("i","k") 
    elif "j" in data: 
     data = data.replace("j","l") 
    elif "k" in data: 
     data = data.replace("k","m") 
    elif "l" in data: 
     data = data.replace("l","n") 
    elif "m" in data: 
     data = data.replace("m","o") 
    elif "n" in data: 
     data = data.replace("n","p") 
    elif "o" in data: 
     data = data.replace("o","q") 
    elif "p" in data: 
     data = data.replace("p","r") 
    elif "q" in data: 
     data = data.replace("q","s") 
    elif "r" in data: 
     data = data.replace("r","t") 
    elif "s" in data: 
     data = data.replace("s","u") 
    elif "t" in data: 
     data = data.replace("t","v") 
    elif "u" in data: 
     data = data.replace("u","w") 
    elif "v" in data: 
     data = data.replace("v","x") 
    elif "w" in data: 
     data = data.replace("w","y") 
    elif "x" in data: 
     data = data.replace("x","z") 
    print data 

腳本讀取一個名爲crypto的txt文件,並開始根據上述語句替換字符。文件裏面寫着阿羅哈這個詞。

這是結果我得到每次我運行該腳本

clohc 
elohe 
glohg 
ilohi 
iloji 
klojk 

如何解決呢?

+0

閱讀[問]和[mcve] – Julien

+0

「替換字符」的定義不明確。上述示例的具體要求是什麼以及您的預期結果是什麼? – kaylum

+0

看起來你試圖實現什麼更通常稱爲凱撒密碼或旋轉密碼 –

回答

1

什麼Python的 string translate

import string 
with open("crypto.txt","r") as arquivo: 
    data = arquivo.read() 
    out = data.translate(string.maketrans("abcdefghijklmnopqrstuvw","defghijklmnopqrstuvwxyz")) 
    print out 

它直接equlal到perl tr功能。這是作品如下

圖片介紹A轉換爲TC轉換爲GG轉換爲CT轉換爲A

那就不要用字符串混淆翻譯和字符串替換

字符串替換,替換整個單詞。字符串翻譯,由每個字符替換。