您可以使用str.replace
创建子的双出线索每一行,然后遍历更换后重新分配到行的更新值:
with open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
clues = [list(line.rstrip()) for line in f]
for line in f2:
for rep, orig in clues:
line = line.replace(orig, rep)
print(line.rstrip())
输出:
A+/084&"
A3MANA+
8N203:
,1$&
!-MN
.A7&33&
AMA71N
&-&641'2
A))85
9&330M
或者使用str.translate:
with open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
# keys are ord of character to replace,
# values are character to replace with
d = {ord(k): v for v, k in (list(line.rstrip()) for line in f)}
for line in f2:
print(line.translate(d).rstrip())
输出:
A+/084&"
A3MANA+
8N203:
,1$&
!-MN
.A7&33&
AMA71N
&-&641'2
A))85
9&330M
对于需要使用string.maketrans
创建表python2:
from string import maketrans
with open("clues.txt", 'r') as f, open("words.txt", 'r') as f2:
# separate A -> # ...
a, b = zip(*(list(line.rstrip()) for line in f))
# create table where # maps to A, * -> M and % -> N
tbl = maketrans("".join(b), "".join(a))
for line in f2:
# translate each string using our mapping table
print(line.translate(tbl).rstrip())
输出:
A+/084&"
A3MANA+
8N203:
,1$&
!-MN
.A7&33&
AMA71N
&-&641'2
A))85
9&330M
Python3需要的字符的ord
的映射替换为你想要替换的字符串,在python 2中我们做了类似的事情,但必须使用string.maketrans来创建我们的表,最终成为字符串'#*%', 'AMN'
。