2016-10-09 116 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。非常感谢 –