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

查看:133
本文介绍了在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 '\033[1m' + 'Hello World!' + '\033[0m'

并获得:

Hello World!

(无黑体).颜色也不起作用.但是:

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

print '\033[4m' + 'Hello World!' + '\033[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 Notebook中,解决此问题的一种干净方法是使用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))

然后做一些很酷的事情

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

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

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

为澄清起见,尽管我们使用markdown,但这是一个 code 单元:您可以执行以下操作:

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笔记本电脑中.

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

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

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