是否可以在 ipython 的 Notebook 中使用不同颜色进行打印?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16816013/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:44:40  来源:igfitidea点击:

Is it possible to print using different colors in ipython's Notebook?

pythonjupyter-notebook

提问by Rabarberski

Is it somehow possible to have certain output appear in a different color in the IPython Notebook? For example, something along the lines of:

是否有可能在 IPython Notebook 中以不同的颜色显示某些输出?例如,类似于以下内容:

 print("Hello Red World", color='red')

采纳答案by Matt

The notebook has, of course, its own syntax highlighting. So I would be careful when using colour elsewhere, just to avoid making things harder to read for yourself or someone else (e.g., output should simply be in black, but you get parts in red if there is an exception).

当然,笔记本有自己的语法突出显示。所以在其他地方使用颜色时我会小心,只是为了避免让自己或其他人更难阅读(例如,输出应该只是黑色,但如果有例外,你会得到红色部分)。

But (to my surprise), it appears that you can use ANSI escape codes (even in the browser). At least, I could:

但是(令我惊讶),您似乎可以使用 ANSI 转义码(即使在浏览器中)。至少,我可以:

On the default Python prompt:

在默认的 Python 提示符下:

>>> print("\x1b[31m\"red\"\x1b[0m")
"red"

In the notebook:

在笔记本中:

In [28]: print("\x1b[31m\"red\"\x1b[0m")
         "red"

(Obviously, I cheated here with the syntax highlighting of SO so that "red" is printed in the colour red in both examples. I don't think SO allows a user to set a colour for text.)

(显然,我在这里用 SO 的语法突出显示作弊,以便在两个示例中都以红色打印“红色”。我认为 SO 不允许用户为文本设置颜色。)

I wouldn't really know another way to get colours.

我真的不知道另一种获得颜色的方法。

For more on ANSI escape codes, I'd suggest the Wikipedia article. And if you find the above to verbose, you can of course write a wrapper function around this.

有关 ANSI 转义码的更多信息,我建议阅读维基百科文章。如果你发现上面的内容很冗长,你当然可以围绕它编写一个包装函数。

回答by Matt

Not with raw Python print. You will have to define a _repr_html_on an object and return it or call IPython.lib.display(object_with_repr_html).

不适用于原始 Python 打印。您必须_repr_html_在对象上定义 a并返回它或调用IPython.lib.display(object_with_repr_html)

I guess you could overwrite the built-in print to do it automatically...

我想您可以覆盖内置打印以自动执行...

You could inspire from http://nbviewer.ipython.org/5098827, code in a gist on github, ML discussion here.

您可以从http://nbviewer.ipython.org/5098827、github上的要点中的代码此处的ML 讨论中获得启发。

回答by alvas

Here's a quick hack:

这是一个快速的黑客:

from IPython.display import HTML as html_print

def cstr(s, color='black'):
    return "<text style=color:{}>{}</text>".format(color, s)

left, word, right = 'foo' , 'abc' , 'bar'
html_print(cstr(' '.join([left, cstr(word, color='red'), right]), color='black') )

[out]:

[出去]:

enter image description here

enter image description here

If you just want a single color: html_print(cstr('abc', 'red'))

如果你只想要一种颜色: html_print(cstr('abc', 'red'))

回答by anand tripathi

You can use this library termcolorand you can get all other official libraries of python in PyPi

您可以使用这个库termcolor并且您可以在 PyPi 中获取所有其他官方 Python 库

See the documentation in pypi.python.org or follow these steps

请参阅 pypi.python.org 中的文档或按照以下步骤操作

  1. pip install termcolor
  2. then goto ipython
  1. pip 安装 termcolor
  2. 然后转到 ipython

Code

代码

from termcolor import colored
print(colored('hello', 'red'), colored('world', 'green'))
print(colored("hello red world", 'red'))

Output:

输出:

hello world
hello red world

The first argument is what you want to print on console and second argument use that color

第一个参数是您要在控制台上打印的内容,第二个参数使用该颜色

回答by Roei Bahumi

Using @Evert answer, here is a method that would wrap a list of tokens in red and return a highlighted string

使用@Evert 答案,这里有一种方法可以将标记列表包装为红色并返回突出显示的字符串

def color_in_tokens(tokens, color_token_contains="_"):
  """
  Highlights the tokens which contain 'color_token_contains'

  :param tokens: list of strings
  :param color_token_contains: str (the string for marking a token red)
  :return: str
  """
  return " ".join(["\x1b[31m%s\x1b[0m" % i if color_token_contains in i else i for i in tokens])

Just call print on the returned string: enter image description here

只需在返回的字符串上调用 print : enter image description here

回答by Kourosh Meshgi

Similar to what @alvas mentioned but simpler

类似于@alvas 提到的但更简单

from IPython.display import Markdown
display (Markdown('this is in <span style="color: #ff0000">red</span> color.'))

回答by Zags

There is the colored library(pip install colored), which you can use to modify a string to get color codes to modify how it is printed. Example use:

彩色库( pip install colored),您可以使用它来修改字符串以获取颜色代码以修改其打印方式。使用示例:

import colored
print(colored.bg("white") + colored.fg("red") + "Hello world!")

回答by geekazoid

coloramamakes it dead easy:

colorama让它变得容易:

from colorama import Fore
print(Fore.RED + "this is red")

回答by miki

Thanks to @alvas function and adding another function we get a very simple way to print

感谢@alvas 函数并添加另一个函数,我们得到了一种非常简单的打印方式

from IPython.display import HTML as html_print
from IPython.display import display

def cstr(s, color='black'):
    return "<text style=color:{}>{}</text>".format(color, s)

def print_color(t):
    display(html_print(' '.join([cstr(ti, color=ci) for ti,ci in t])))

print_color((('hello my name is', 'black'),('jhjfd','red')))
print_color((('hello my name is', 'green'),))

enter image description here

enter image description here

回答by Harvey

Text in red:

红色文字:

print("\x1b[31mText in red")

Text in bold:

粗体文本:

print("\x1B[1mText in bold")

Text in underline

下划线文字

print("\x1B[4mText in underline")

See hereunder Styles and Colors chapter and see what works for you. RGB colors didn't work for me.

请参阅样式和颜色章节下的此处,看看哪些适合您。RGB 颜色对我不起作用。