I'm working on decrypting a substitution cipher (not Caesar/ROT) with frequency analysis and no specialized tools. Let's say I wanted to use this cipher dictionary which seems good enough after analysis:
key = {
'S':'E',
'Q':'A',
'J':'T',
'U':'O',
'B':'I',
'N':'N',
'C':'L',
'G':'R',
'D':'H',
'V':'S',
'Z':'D',
'W':'C',
'M':'U',
'Y':'M',
'T':'F',
'X':'P',
'K':'G',
'E':'W',
'L':'Y',
'A':'B',
'F':'V',
'I':'K',
'O':'X',
'H':'J',
'R':'Q',
'P':'Z'
}
My code below has an obvious problem:
with open(filename) as f:
out = f.read()
for k in key:
out = out.replace(k,key[k])
print out
Because it replaces every character one after the other, a character at a certain position gets replaced several times before the algorithm is done, instead of just once.
(ie: first iteration the algorithm will replace all S
with E
, but then it reaches E
in the dictionary and replaces all E
s with W
)
Does Python have a convenient way of doing this operation in one shot? Or will I be forced to keep track of the positions that have already been changed myself?