我在尝试替换文件中的字符时遇到了麻烦。
#!/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文件,并开始根据上述语句替换字符。文件里面写着aloha这个词。
这是我每次运行脚本时得到的结果
clohc
elohe
glohg
ilohi
iloji
klojk
我该如何解决?
答案 0 :(得分:1)
python的 string translate
怎么样?sudo service nginx restart
它与perl import string
with open("crypto.txt","r") as arquivo:
data = arquivo.read()
out = data.translate(string.maketrans("abcdefghijklmnopqrstuvw","defghijklmnopqrstuvwxyz"))
print out
函数直接相同。它的工作原理如下
图片描述tr
转换为A
,T
转换为C
,G
转换为G
和C
转换到T
然后不要混淆字符串翻译和字符串替换
字符串替换,替换整个单词。字符串翻译,由每个字符替换。