Multiple string replacement...

Stephen Kloder stephenk at cc.gatech.edu
Fri Sep 22 12:41:55 EDT 2000


Simon Brunning wrote:

> I'm trying to put together a script which will replace values in files. The
> idea is that you can specify multiple replacements at once. For example you
> can replace 'Spam' with 'eggs' and 'Jesus' with 'Brian' in one pass.
>
> So, I read the replacement sets in from a file, and store them in a list of
> lists, thus:
>
> replacements = [['Spam', 'eggs,], ['Jesus', 'Brian']]
>
> Then I read in my file data, and do:
>
> for replacement in replacements:
>         filedata = filedata.replace(replacement[0], replacement[1])
>
> This all works OK, except...
>
> I set up a ROT13 replacement set, which looks like:
> [['A', 'N'], ['B', 'O'], ['C', 'P'], ['D', 'Q'], ['E', 'R'], ['F', 'S'],
> ['G', 'T'], ['H', 'U'], ['I', 'V'], ['J', 'W'], ['K', 'X'], ['L', 'Y'],
> ['M', 'Z'], ['N', 'A'], ... and so on. The problem here is that after 'A'
> and been replaced by 'N', it gets replaced back again.
>
> Anyone got a cunning plan?
>

I see you've already been told to you translate if you're doing a
character-by-character replacement.  For strings, I reccomend using a regex and
a dictionary:
import re
from string import join
replacements = {'Spam', 'eggs': 'Jesus': 'Brian'}
#read data into string str
re.sub(join(replacements.keys(),'|'),lambda x:replacements[x.group()],str)

Of course, if you will be using the same methods multiple time, you might want
to precompile the regex:
p=re.compile(join(replacements.keys(),'|'))
p.sub(lambda x:replacements[x.group()],str)

--
Stephen Kloder               |   "I say what it occurs to me to say.
stephenk at cc.gatech.edu       |      More I cannot say."
Phone 404-874-6584           |   -- The Man in the Shack
ICQ #65153895                |            be :- think.




More information about the Python-list mailing list