开发者

text output with color [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. Closed 11 years ago.

Fellow programmers, I am running a Monte Carlo type simulation in python that generates long strings of 0,1, and 2's and I'm trying to output them in a text or html file for further analysis.

I'd like to print these strings in an external file, and use different colors for the different digits. Say, 0 = red, 1 = green, and 2 = two.

My knowledge of Python, and html is somehow limited. Any "pointers"(sorry for unintentional pun) and sample bits of code will be very welcome.开发者_运维百科


just write to a file like this and open it in a webbrowser:

def write_red(f, str_):
    f.write('<p style="color:#ff0000">%s</p>' % str_)

def write_blue(f, str_):
    # ...

f = open('out.html', 'w')
f.write('<html>')

write_red(f, thing_i_want_to_be_red_in_output)

f.write('</html>')
f.close()

Update: To make this answer complete, with the use of css, the output file can be much smaller.

style = """<style type='text/css'>
html {
  font-family: Courier;
}
r {
  color: #ff0000;
}
g {
  color: #00ff00;
}
b {
  color: #0000ff;
}
</style>"""

RED = 'r'
GREEN = 'g'
BLUE = 'b'

def write_html(f, type, str_):
    f.write('<%(type)s>%(str)s</%(type)s>' % {
            'type': type, 'str': str_ } )

f = open('out.html', 'w')
f.write('<html>')
f.write(style)

write_html(f, RED, 'My name is so foo..\n')
write_html(f, BLUE, '102838183820038.028391')

f.write('</html>')
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜