William Allison wrote:
> 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()
There is no need to process the file a line at a time unless it is too
big to fit in memory. I would read it all at once:
in_put = open('test.html', 'r')
data = in_put.read()
in_put.close()
data = data.replace("TWY", "<b><font color='#FF0000'>TWY</font></b>")
data = data.replace("RWY", "<b><font color='#FF0000'>RWY</font></b>")
data = data.replace("WIP", "<b><font color='#FF0000'>WIP</font></b>")
out_put = open('test_highlight.html', 'a')
out_put.write(data)
out_put.close()
Since the replacements are so similar, you could do all three with a
single regular expression replace:
import re
data = re.sub('TWY|RWY|WIP', r"<b><font color='#FF0000'>\0</font></b>",
data)
I don't see a strong reason to prefer any one of these; my preference is
for the last because it is short and doesn't repeat the substitution text.
Kent
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor