【问题标题】:Make output cells like Markdown制作像 Markdown 这样的输出单元格
【发布时间】:2012-12-07 20:19:52
【问题描述】:

我喜欢 IPython 的 Markdown 单元格,用于在笔记本中合并 HTML 和其他丰富的内容。我想知道命令输出是否可以在输出单元格中进行类似的格式化。

这是我输出 HTML 的函数之一:

    print_html():
      print """
      <h2>Matplotlib's chart gallery (Click a chart to see the code to create it)</h2><br>
      <div align="center"> <iframe title="Matplotlib Gallery" width="950"
      height="250" src="http://matplotlib.org/gallery.html#api" frameborder="0"
      allowfullscreen></iframe></div>
    """

上面的 HTML 代码,如果放在 markdown(输入)单元格中,会产生到 Matplotlib 库的很好的链接。但在输出单元格中,它只是纯文本。有什么办法让它内容丰富?

【问题讨论】:

  • 目前的解决方案仅适用于您直接从 IPython 调用的函数 - 如果我们想在从函数内调用的打印/记录方法中呈现 html 怎么办?

标签: ipython-notebook


【解决方案1】:

在这里找到解决方案:http://mail.scipy.org/pipermail/ipython-user/2012-April/009838.html

在此处引用解决方案以供参考:

布莱恩·格兰杰:

" 让函数返回包装在 HTML 对象中的原始 HTML:

from IPython.core.display import HTML
...
...
def foo():
    raw_html = "<h1>Yah, rendered HTML</h1>"
    return HTML(raw_html)

"

现在调用 foo() 确实可以提供我想要的丰富格式的 html。

【讨论】:

  • 链接邮件指出,您需要按如下方式导入 HTML:from IPython.core.display import HTML
  • 感谢您改进此答案!
  • 但是你不能把它和一些印刷品混在一起。所以就像制作一个标题并在下面打印一些文本
  • 您不一定必须使用打印。只需将您想要打印的任何内容添加到 raw_html 字符串,然后返回 HTML(raw_html)
  • 请注意,您也可以使用 markdown 代替 HTML。首先,导入 Markdown:from IPython.core.display import Markdown,然后,在最后一行返回你的 Markdown 内容Markdown(your_content_here)
【解决方案2】:

最近在此处的博客文章中发布了某种更高级的解决方案:

http://guido.vonrudorff.de/ipython-notebook-code-output-as-markdown/

它创建并注册了一个新的 IPython 魔法%%asmarkdown。您使用此命令添加的每个代码单元的输出将像纯降价单元一样呈现。使用原始问题的内容,以下行为将按预期进行:

%%asmarkdown
print """
<h2>Matplotlib's chart gallery (Click a chart to see the code to create it)</h2><br>
<div align="center"> <iframe title="Matplotlib Gallery" width="950"
height="250" src="http://matplotlib.org/gallery.html#api" frameborder="0"
allowfullscreen></iframe></div>
"""

【讨论】:

  • 这非常容易。对于 python 3 用户,添加 from io import StringIO 而不是 from stringIO import StringIO 的小例外。
  • 这是最能回答原始问题的解决方案。
【解决方案3】:

只是为您的代码示例添加一些额外的功能

htmlContent = ''

def header(text):
    raw_html = '<h1>' + str(text) + '</h1>'
    return raw_html

def box(text):
    raw_html = '<div style="border:1px dotted black;padding:2em;">'+str(text)+'</div>'
    return raw_html

def addContent(raw_html):
    global htmlContent
    htmlContent += raw_html


# Example
addContent( header("This is a header") )
addContent( box("This is some text in a box") )

from IPython.core.display import HTML
HTML(htmlContent)

给你这个:

【讨论】:

  • 很高兴看到这些花哨的功能!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2021-04-09
  • 1970-01-01
  • 2016-10-23
  • 1970-01-01
  • 2020-05-27
相关资源
最近更新 更多