Oltmans wrote:
Hi,
I'm new to Python (and admittedly not a very good programmer) and I've
come across a scenario where I've to search and replace text in a
file.
For the sake of an example, I'm searching for every occurence of the
text
[[http://www.hotmail.com -> Hotmail]]
I've to replace it with
[http://www.hotmail.com Hotmail]
I've come up with following scheme
p=re.compile(r'\[\[')
q=re.compile(r'->')
p.sub('[',txt)
q.sub('\b',txt)
Give that I don't have very strong RegEX background, this doesn't look
very elegant. Is there some other way I can accomplish the same thing?
Moreover, please note that I'm using 'p' and 'q' for two regex and
then calling 'sub()' on both p and q. Can't I just do that by
employing one RegEx and then calling sub() only once?
Please enlighten me. Thanks in advance.
If you really want to replace EVERY occurrence, no regexes are needed.
I'd do something like (not tested):
fp=open(inputfilename, 'r')
contents=fp.read()
fp.close()
parts=contents.split('[[http://www.hotmail.com -> Hotmail]]')
newcontents='[http://www.hotmail.com Hotmail]'.join(parts)
fp=open(outputfilename, 'w')
fp.write(newcontents)
fp.close()
-Larry
--
http://mail.python.org/mailman/listinfo/python-list