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


Groups > comp.lang.python > #2639

Re: replace regex in file using a dictionary

References <c0082545-84a6-4bc5-b734-1c0f89ae27cd@r4g2000prm.googlegroups.com>
Date 2011-04-05 10:32 +0200
Subject Re: replace regex in file using a dictionary
From Vlastimil Brom <vlastimil.brom@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.38.1301992333.9059.python-list@python.org> (permalink)

Show all headers | View raw


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

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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

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

csiph-web