replace regex in file using a dictionary

Vlastimil Brom vlastimil.brom at gmail.com
Tue Apr 5 04:32:11 EDT 2011


2011/4/5 Martin De Kauwe <mdekauwe at gmail.com>:
> Hi,
>
> So i want to replace multiple lines in a text file and I have reasoned
> the best way to do this is with a dictionary. I have simplified my
> example and broadly I get what I want however I am now printing my
> replacement string and part of the original expression. I am guessing
> that I will need to use a more complicated expression than I am
> currently am to achieve what I want?
>
> my aim is to match the expression before the "=" and replace the
> string after the equals...
>
> My failed example...
> [...]
>
> thanks.
> --
>

Hi,
I guess, you would have to split the line and extract the substrings
before and after "=" and replace only the value part.
Or you can use regular expression replace with a replacement function,
e.g. like the following sample.
The re pattern would probably need some tweaking to match the variable
names, the values and the whitespace around "="; and, of course, it
shouldn't match anything unwanted in the original text  ...

hth,
  vbr
####################################

import re

orig_str = """structcn = 150.0
metfrac0 = 0.85
unknown7 = 38.2
"""

replacement_dict = {"structcn": "999.0", "metfrac0": "0.85"}

def repl_fn(m):
    return m.group(1) + m.group(2) + replacement_dict.get(m.group(1),
m.group(3))

new_str = re.sub(r"([\w\d_]+?)( = )([\d.-]+)", repl_fn, orig_str)

print new_str

####################################



More information about the Python-list mailing list