replace regex in file using a dictionary

Yashwin Kanchan yashwinkanchan at gmail.com
Tue Apr 5 06:21:03 EDT 2011


How about creating a new string instead of replacing the original.

def replace_keys(text, replacements_dict):
    text_list = text.split('\n')
    new_text = ''
    for line in text_list:
        key=line.split('=')[0]
        if key.strip() in replacements_dict:
            new_text = new_text + key + '=' + replacements_dict[key.strip()]
+ "\n"
        else:
            new_text = new_text + line
    return new_text


On 5 April 2011 09:32, Vlastimil Brom <vlastimil.brom at gmail.com> wrote:

> 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
>
> ####################################
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20110405/c2a3294e/attachment.html>


More information about the Python-list mailing list