18

我喜欢 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 库的很好的链接。但在输出单元格中,它只是纯文本。有什么办法让它丰富的内容?

4

3 回答 3

20

在这里找到了解决方案: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。

于 2012-12-07T20:43:59.007 回答
7

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

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>
"""
于 2015-10-24T02:07:46.317 回答
4

只需在您的代码示例中添加一些额外的功能

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)

给你这个:

输出

于 2013-07-26T06:56:34.653 回答