您可以使用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'
。