[Tutor] Better way to substitute text?

Shantanoo Mahajan shantanoo at gmail.com
Sat Sep 30 08:45:21 CEST 2006


+++ William Allison [29-09-06 18:55 -0400]:
| Hi,
| Just learning Python, on chapter 6 of Learning Python 2nd Ed.  So, on to 
| the question.  Is there a better way to
| implement the code below?  It scans a saved html file and highlights 
| certain keywords is a bold, red font.  It works,
| but I suppose I'm wondering if it's the "Pythonic" way.
| Thanks,
| Will
| 
| #!/usr/bin/env python
| 
| in_put = open('test.html', 'r')
| out_put = open('test_highlight.html', 'a')

===================================== 
| for line in in_put:
|         line = line.replace("TWY", "<b><font 
| color='#FF0000'>TWY</font></b>")
|         line = line.replace("RWY", "<b><font 
| color='#FF0000'>RWY</font></b>")
|         line = line.replace("WIP", "<b><font 
| color='#FF0000'>WIP</font></b>")
|         out_put.write(line)
===================================== 
| 
| in_put.close()
| out_put.close()


replace_words = ['TWY', 'RWY', 'WIP']
for line in in_put:
        for replace_word in replace_words:
                out_put.write(line.replace(replace_word,"<b><font color='#FF0000'>"+replace_word+"</font></b>"))

You can furthur reduce for loops.

Shantanoo
-- 
Always have an answer to the question, "What would I do if I lost my job
tomorrow?"


More information about the Tutor mailing list