You can make it simpler by not splitting the input file into lines.
Treat it as a single string.
in_put = open('test.html', 'r').read()
replace_words = ['TWY', 'RWY', 'WIP']
for replace_word in replace_words:
in_put = in_put.replace(replace_word, "<b><font
color='#FF0000'>" + replace_word + "</font></b>")
open('test_highlight.html', 'a').write(in_put)
-----Original Message-----
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On
Behalf Of William Allison
Sent: Saturday, September 30, 2006 8:10 AM
To: [email protected]
Subject: Re: [Tutor] Better way to substitute text?
Shantanoo Mahajan wrote:
> +++ 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
>
Thanks Shantanoo,
I like that a lot better. Had to modify it just a little.
replace_words = ['TWY', 'RWY', 'WIP']
for line in in_put:
for replace_word in replace_words:
line = line.replace(replace_word, "<b><font
color='#FF0000'>" + replace_word + "</font></b>")
out_put.write(line)
I can never quite get when to use a nested loop.
Thanks again,
Will
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor