【问题标题】:Is it possible to print using different colors in ipython's Notebook?是否可以在 ipython 的 Notebook 中使用不同的颜色进行打印?
【发布时间】:2013-05-24 20:07:54
【问题描述】:

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

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

【问题讨论】:

    标签: python jupyter-notebook


    【解决方案1】:

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

    我猜你可以覆盖内置的 print 来自动完成...

    您可以从http://nbviewer.ipython.org/5098827、代码in a gist on github、ML 讨论here 中获得启发。

    【讨论】:

    • @Evert 的代码在 ipython notebook 的当前 head 版本中工作——我们可以假设这个功能已经被添加了吗?
    • 对,ANSI转义码的解析有一段时间了,忘记了。
    【解决方案2】:

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

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

    在默认的 Python 提示符下:

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

    在笔记本中:

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

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

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

    有关 ANSI 转义码的更多信息,我建议使用 Wikipedia article。如果你发现上面的内容很冗长,你当然可以围绕它编写一个包装函数。

    【讨论】:

    • @cgseller 对于终端笔记本 (jupyter console) 中的 IPython 5.1.0,这仍然适用于我。您指的是什么笔记本和版本?
    • 如果它也适合你,那就太好了。我只确认了最新的
    • @laike9m 请提及您的 Jupyter 版本,以及您运行笔记本的方式。
    • 我使用最新版本(昨天通过 pip 安装)并使用jupyter notebook 运行。
    • @laike9m 我刚刚在各种浏览器(macOS 上)中使用 Python 3.6 和 Jupyter 4.4.1 (IPython 5.3.0) 进行了测试。我的答案中的示例仍然适用于所有情况。我假设您复制粘贴了示例,以避免拼写错误?您的配置中可能有一些东西,在这种情况下,您可能想在 StackOverflow 上提出一个关于它的新问题。不过,您可能必须深入研究各种配置细节才能得到答案。
    【解决方案3】:

    这里有一个快速的技巧:

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

    [出]:

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

    【讨论】:

      【解决方案4】:

      你可以使用这个库termcolor,你可以在PyPi中获取所有其他官方的python库。

      1. pip install termcolor
      2. 然后转到ipython

      代码

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

      输出:

      hello world
      hello red world
      

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

      有关更多信息,请参阅pypi.python.org 中的文档

      【讨论】:

      • 它可以在 Jupyter 笔记本中使用吗?还是只有 Jupyter 解释器?
      • 两者都适用,唯一的就是你必须有那个库 termcolor
      • 有趣,您使用的是哪个 Jupyter 版本? ANSI 在 Jupyter notebook 中的另一台笔记本电脑上无法运行。
      • colorama 是另一个类似的库,可让您执行 print(Fore.RED + 'some red text'); print(Back.GREEN + 'and with a green background')print(colored('Hello, World!', 'green', 'on_red')) 之类的操作。
      • 有效但只支持七种颜色:红、绿、黄、蓝、洋红、青、白
      【解决方案5】:

      使用@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])
      

      只需在返回的字符串上调用 print:

      【讨论】:

        【解决方案6】:

        与@alvas 提到的类似,但更简单

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

        【讨论】:

        • 因为问题专门针对 Jupyter 笔记本,所以这应该是 答案
        • 同意,不需要额外的库
        • 它不适用于 VS Code 笔记本。如果我使用 HTML 而不是 Markdown 一切正常。
        【解决方案7】:

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

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

        【讨论】:

          【解决方案8】:

          colorama 让一切变得简单:

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

          【讨论】:

            【解决方案9】:

            感谢@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'),))
            

            【讨论】:

              【解决方案10】:

              红色文字:

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

              粗体字:

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

              下划线文字

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

              请参阅样式和颜色一章下的here,看看什么适合您。 RGB 颜色对我不起作用。

              【讨论】:

                【解决方案11】:

                取自:Standard for ANSI Colors in Terminals

                这个sn-p可以在一行中显示所有颜色:

                RESET = "\x1b[0m"
                print("To reset attributes: \\x1b[0m\n")
                for i in range(0, 8):
                    print("\x1b[1;3{0}m\\x1b[1;3{0}m{1} \x1b[0;3{0}m\\x1b[0;3{0}m{1} "
                          "\x1b[1;4{0};3{0}m\\x1b[1;3{0};4{0}m{1}".format(i, RESET))
                

                【讨论】:

                  【解决方案12】:

                  在 Jupiter notebook 中,我们可以使用颜色标记以不同的颜色打印输出 我们可以通过三种方式使用颜色标记。

                  让我们看看如何在笔记本上打印黄色。

                  1. print('\033[93m output')
                  2. print('\033[93m' 'output')
                  3. print('\033[93m' + 'output')

                  一些颜色是:

                  • 黄色 = '\033[93m'
                  • 绿色 = '\033[92m'
                  • 红色 = '\033[91m'
                  • 蓝色 = '\033[94m'
                  • 粉红色 = '\033[95m'

                  您可以更改最后一个数字并获得其他颜色。

                  【讨论】:

                    【解决方案13】:

                    一个不错的方法是使用pandas:

                    import pandas as pd
                    def apply_formatting(col, hex_colors):
                        for hex_color in hex_colors:
                            if col.name == hex_color:
                                return [f'background-color: {hex_color}' for c in col.values]
                                    
                    def display_hex_colors(hex_colors: List[str]):
                        df = pd.DataFrame(hex_colors).T
                        df.columns = hex_colors
                        df.iloc[0,0:len(hex_colors)] = ""
                        display(df.style.apply(lambda x: apply_formatting(x, hex_colors)))
                    
                    hex_list = ['#FFFFFF', '#F0F0F0', '#FCF0D8', '#fdd8a7', '#fdc38d', '#fca16c',
                                '#f67b51', '#e7533a', '#cf2518', '#ad0000', '#7f0000', '#440402']
                    display_hex_colors(hex_list)
                    

                    示例输出:

                    【讨论】:

                      猜你喜欢
                      • 2018-04-01
                      • 1970-01-01
                      • 2012-12-15
                      • 1970-01-01
                      • 1970-01-01
                      • 2016-10-15
                      • 1970-01-01
                      • 2014-08-17
                      • 2012-02-15
                      相关资源
                      最近更新 更多