Regular expressions in a Python find-and-replace script?

Posted by Haidon on Stack Overflow See other posts from Stack Overflow or by Haidon
Published on 2010-06-14T11:10:27Z Indexed on 2010/06/14 11:12 UTC
Read the original article Hit count: 220

Filed under:
|
|

I'm new to Python scripting, so please forgive me in advance if the answer to this question seems inherently obvious.

I'm trying to put together a large-scale find-and-replace script using Python. I'm using code similar to the following:

findreplace = [
('term1', 'term2'),
]

inF = open(infile,'rb')
s=unicode(inF.read(),charenc)
inF.close()

for couple in findreplace:
    outtext=s.replace(couple[0],couple[1])
    s=outtext

outF = open(outFile,'wb')
outF.write(outtext.encode('utf-8'))
outF.close()

How would I go about having the script do a find and replace for regular expressions?

Specifically, I want it to find some information (metadata) specified at the top of a text file. Eg:

Title: This is the title
Author: This is the author
Date: This is the date

and convert it into LaTeX format. Eg:

\title{This is the title}
\author{This is the author}
\date{This is the date}

Maybe I'm tackling this the wrong way. If there's a better way than regular expressions please let me know!

Thanks!

© Stack Overflow or respective owner

Related posts about python

Related posts about regex