在 ipython qtconsole 中打印粗体、彩色等文本 [英] printing bold, colored, etc., text in ipython qtconsole

查看:32
本文介绍了在 ipython qtconsole 中打印粗体、彩色等文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让文本在 ipython 的 qtconsole 中显示为粗体、颜色或斜体.

I'm trying to get text to display as bold, or in colors, or possibly in italics, in ipython's qtconsole.

我找到了这个链接:如何在 Python 中打印粗体文本?,并使用第一个和第二个答案,但在 qtconsole 中,只有下划线选项有效.

I found this link: How do I print bold text in Python?, and used the first and second answers, but in qtconsole, only the underlining option works.

我尝试:

print '33[1m' + 'Hello World!'+ '33[0m'

并得到:

Hello World!

(无粗体).颜色也不行.但是:

(No boldface). The colors don't work either. But:

print '33[4m' + 'Hello World!'+ '33[0m'

并得到:

Hello World!

带下划线.

这只是在 qtconsole 中.仅在终端中运行 ipython,它可以通过这种方式进行粗体和颜色处理.

This is only in the qtconsole. Running ipython just in the terminal, it works to do boldface and color in this way.

在该链接和另一个中建议了其他选项,在终端中打印使用 Python 的颜色?,从它链接,但它们看起来更复杂,并且使用更精细的包,而不是我想做的事情似乎是必要的,这只是为了让 qtconsole 像普通终端一样显示.

There were other options suggested in that link and another, Print in terminal with colors using Python?, linked from it, but they all seem more complex, and to use more elaborate packages, than seems necessary for what I want to do, which is simply to get qtconsole to display like the ordinary terminal does.

有人知道这是怎么回事吗?这仅仅是qtconsole的限制吗?

Does anyone know what's going on? Is this simply a limitation of the qtconsole?

推荐答案

在 Jupyter Notebooks 中,解决此问题的一种简洁方法是使用 Markdown:

In Jupyter Notebooks, one clean way of solving this problem is using markdown:

from IPython.display import Markdown, display
def printmd(string):
    display(Markdown(string))

然后执行以下操作:

printmd("**bold text**")

当然,这对于粗体、斜体等非常有用,但是markdown本身并没有实现颜色.但是,您可以将 html 放在 Markdown 中,然后得到如下内容:

Of course, this is great for bold, italics, etc., but markdown itself does not implement color. However, you can place html in your markdown, and get something like this:

printmd("<span style='color:red'>Red text</span>")

您也可以将其包装在 printmd 函数中:

You could also wrap this in the printmd function :

def printmd(string, color=None):
    colorstr = "<span style='color:{}'>{}</span>".format(color, string)
    display(Markdown(colorstr))

然后做一些很酷的事情,比如

And then do cool things like

printmd("**bold and blue**", color="blue")

对于颜色,您也可以使用十六进制表示法(例如,color = "#00FF00" 表示绿色)

For the colors, you can use the hexadecimal notation too (eg. color = "#00FF00" for green)

澄清一下,虽然我们使用 markdown,但这是一个代码单元格:您可以执行以下操作:

To clarify, although we use markdown, this is a code cell: you can do things like:

for c in ('green', 'blue', 'red', 'yellow'):
    printmd("Writing in {}".format(c), color=c)

当然,这种方法的一个缺点是依赖于 Jupyter notebook.

Of course, a drawback of this method is the reliance on being within a Jupyter notebook.

这篇关于在 ipython qtconsole 中打印粗体、彩色等文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆