Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #2636 > unrolled thread

replace regex in file using a dictionary

Started byMartin De Kauwe <mdekauwe@gmail.com>
First post2011-04-05 00:59 -0700
Last post2011-04-05 16:12 -0700
Articles 4 — 3 participants

Back to article view | Back to comp.lang.python


Contents

  replace regex in file using a dictionary Martin De Kauwe <mdekauwe@gmail.com> - 2011-04-05 00:59 -0700
    Re: replace regex in file using a dictionary Vlastimil Brom <vlastimil.brom@gmail.com> - 2011-04-05 10:32 +0200
    Re: replace regex in file using a dictionary nn <pruebauno@latinmail.com> - 2011-04-05 08:41 -0700
      Re: replace regex in file using a dictionary Martin De Kauwe <mdekauwe@gmail.com> - 2011-04-05 16:12 -0700

#2636 — replace regex in file using a dictionary

FromMartin De Kauwe <mdekauwe@gmail.com>
Date2011-04-05 00:59 -0700
Subjectreplace regex in file using a dictionary
Message-ID<c0082545-84a6-4bc5-b734-1c0f89ae27cd@r4g2000prm.googlegroups.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...

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.

[toc] | [next] | [standalone]


#2639

FromVlastimil Brom <vlastimil.brom@gmail.com>
Date2011-04-05 10:32 +0200
Message-ID<mailman.38.1301992333.9059.python-list@python.org>
In reply to#2636
2011/4/5 Martin De Kauwe <mdekauwe@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

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

[toc] | [prev] | [next] | [standalone]


#2657

Fromnn <pruebauno@latinmail.com>
Date2011-04-05 08:41 -0700
Message-ID<e6c4e049-bdf3-4518-9e86-93d5033bae06@17g2000prr.googlegroups.com>
In reply to#2636
On Apr 5, 3:59 am, Martin De Kauwe <mdeka...@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'

[toc] | [prev] | [next] | [standalone]


#2675

FromMartin De Kauwe <mdekauwe@gmail.com>
Date2011-04-05 16:12 -0700
Message-ID<a4382b27-e861-4398-8961-c97dd6cabb0f@j35g2000prb.googlegroups.com>
In reply to#2657
yes thanks both work nicely, I will ponder the suggestions.

[toc] | [prev] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web