replace regex in file using a dictionary

  • Thread starter Martin De Kauwe
  • Start date
M

Martin De Kauwe

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.
 
V

Vlastimil Brom

2011/4/5 Martin De Kauwe said:
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

####################################
 
N

nn

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=" ".join(
(key, sep, replacement_dict.get(key, val)))
return '\n'.join(lines)+'\n'
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top