Typophile

Python search & replace script (for commenting TTX-dump)

Arno Enslin

Does anybody know a Python search & replace script, with the help of which I can comment the output of TTX, the name table for example? It should understand regular expressions and keywords for new lines.

To comment out the name table, you need only replace <name> with <!-- <name> and </name> with </name> -->. If fin is the input file and fout the output, then

intext=fin.read()
fout.write("%s" % intext.replace('<name>', '<!-- <name>').replace('</name>', '</name> -->'))

does the job.

If you have many substitutions and you want to perform them in one pass, then regular expressions may be useful indeed. This link discusses how that can be done.

Michel

Added: you need from string import replace.

@ Michel

Thanks. I want to explain the meaning of the namerecords and a few other things in the dumped TTX file. And remember, I don’t know anything about Python. I am searching for a script like this: "http://sourceforge.net/projects/csart/". But it does not support regular expressions. And I also need a keyword for inserting new lines. The Python script shall be started from a batch file, in which is defined, what shall be replaced by what.

I am unaware of ready to use scripts. I normally write my own bash scripts with sed, awk and now also python for such tasks. If you find anything, let us know.

Captured from web.archive.org on 4 Nov 2010. view this capture