[Tutor] Better way to substitute text?
William Allison
allison.william at comcast.net
Sat Sep 30 16:10:02 CEST 2006
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
More information about the Tutor
mailing list