2016-10-09 134 views
1

我正在寫一段python代碼來替換字母表序列。我知道如何去做,但不幸的是,它只是取代了已經取代的。用python替換字符串中的字符串

lines=[] 
replacements = {'a':'s','s':'d','d':'f','f':'g','g':'h','h':'j','j':'k','k':'l'} 

with open("wrongString.txt") as infile: 
    for line in infile: 
     for src,target in replacements.iteritems(): 
      line = line.replace(src,target) 
     lines.append(line) 

with open("decode.txt","w") as outfile: 
     for line in lines:    
      outfile.write(line) 

wrongstring.txt:ASDFGHJKL

運行代碼後,結果顯示(encode.txt):ggggkkkll

的代碼不替換 「a」 至 「S」,並保持替換「s」爲「d」,直到以某種方式獲得「g」。我只是想將「a」替換爲「s」,然後停止替換它。

你們能幫我找到解決辦法嗎?

感謝您的回答!

回答

1

使用列表比較所以你不要覆蓋任何替換的字符:

line = "".join([replacements.get(ch, ch) for ch in line]) 

你也不需要存儲所有的行,只寫線條,當您去:

with open("wrongString.txt") as infile, open("decode.txt","w") as outfile: 
    outfile.writelines("".join([replacements.get(ch,ch) 
            for ch in line]) for line in infile)) 
+1

不錯!它的作用就像一個魅力:D。非常感謝 –