带颜色的文本输出

-2 投票
1 回答
5574 浏览
提问于 2025-04-16 23:52

亲爱的程序员们,

我正在用Python做一种叫做蒙特卡罗模拟的东西,这个模拟会生成一长串的0、1和2。我想把这些字符串输出到一个文本文件或者HTML文件里,以便后续分析。

我希望能把这些字符串打印到外部文件中,并且给不同的数字用不同的颜色。比如,0用红色,1用绿色,2用蓝色。

我对Python和HTML的了解还不太多。如果能给我一些建议(抱歉,没想到会用到这个双关语)和一些示例代码,我会非常感激。

1 个回答

3

只需像这样写入一个文件,然后在网页浏览器中打开它:

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()

更新: 为了让这个回答更完整,使用CSS后,输出的文件可以小很多。

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>')

撰写回答