replace regex in file using a dictionary

Martin De Kauwe mdekauwe at gmail.com
Tue Apr 5 09:59:02 CEST 2011


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.



More information about the Python-list mailing list