我正在编写一段python代码来替换一系列Alphabet。我知道该怎么做但不幸的是它只是替换了已经取代的那个。
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
代码确实替换了#34; a"到" s",并继续更换" s"成为" d"直到得到" g"以某种方式。我只是想取代" a"成为" s"然后停止更换它。
你能帮助我找到解决方案吗?
感谢您的回答!
答案 0 :(得分:1)
使用 list comp ,这样您就不会覆盖任何替换的字符:
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))