How to re replace string variables?

Eric B. sitric at home.com
Thu Sep 9 17:37:12 EDT 1999


Joel, here's a small python script and a test text file.  Running the script
outputs a new file with the changes.  Let me know if this is what you meant.

p.s.  This could probably be done much quicker, but I'm pretty new to Python
too.  It gets the job done!

-Eric B.  (sitric at home.com)

Joel Burton wrote:

> I'm an experienced perl programmer, but new to Python. I'm trying to convert
> over a script that searches a text file, replacing all instances of
> variables (in this case, flagged by a leading $) with the string variable
> with that name.
>
> In perl, I would do this by
>     s/\$([A-za-z]\w*)/${$1}/g
>
> which finds every instances of $xxx and replaces it with the scalar variable
> $xxx.
>
> However, I can't figure out how to do this in Python. Can I refer to a
> variable by referenced name?
>
> I could switch this so that all the variables are in a dictionary, so
> P['one'] = 'uno'
> P['two'] = 'dos', etc.
>
> With a string that looks like: "Is $one the same as $two"?
>
> But I get bogged down with errors when I try things like
>
> re.sub("(\$\w+)",P['\\1'], string)
>
> Because re module, when it gets the repl string/subroutine, hasn't resolved
> what \1 is.
>
> Any help would be very appreciated. Thanks!
>
> Joel Burton
-------------- next part --------------
import string

txtfile = open('test.txt','r')          #your original input file
newfile = open('new.txt','w')           #this will be your output file

testdict={'$var1':'quick','$var2':'jumped','$var3':'sox'}


for zLine in txtfile.readlines():
        for zKey in testdict.keys():
                zLine = string.join(string.split(zLine,zKey), testdict[zKey])

        newfile.write(zLine)
-------------- next part --------------
The $var1 brown fox
$var2 over the big brown box
and ate my smelly brown $var3.

$var1, $var1, to the batcave!


More information about the Python-list mailing list