replace regex in file using a dictionary
nn
pruebauno at latinmail.com
Tue Apr 5 11:41:51 EDT 2011
On Apr 5, 3:59 am, Martin De Kauwe <mdeka... at gmail.com> wrote:
> 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...
>
> def replace_keys(text, replacements_dict):
> for key, var in replacements_dict.iteritems():
> replacement = "%s = %s" % (key, var)
> text = text.replace(key, replacement)
> return text
>
> # example of two lines of the file
> str = \
> """structcn = 150.0
> metfrac0 = 0.85
> """
>
> # replacements
> replacement_dict = {"structcn": "999.0", "metfrac0": "0.85"}
> new_str = replace_keys(str, replacement_dict)
>
> print str
> print
> print new_str
>
> which produces...
>
> structcn = 150.0
> metfrac0 = 0.85
>
> structcn = 999.0 = 150.0
> metfrac0 = 0.85 = 0.85
>
> thanks.
If the structure is very regular you can use something like this:
def replace_keys(text, replacements_dict):
lines=text.splitlines()
for i, row in enumerate(lines):
key, sep, val = row.split()
lines[i]=" ".join(
(key, sep, replacement_dict.get(key, val)))
return '\n'.join(lines)+'\n'
More information about the Python-list
mailing list