IPython `display` 到字符串

IPython `display` to string

我正在尝试使用 IPython.display 模块将对象转换为 Markdown。但是,似乎没有什么好的方法可以将这个 Markdown 导出为字符串。

行为:

>>> from IPython.display import *
>>> from numpy import *
>>> display_markdown(eye(3))
[[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 1.]]

通缉行为:

>>> display_markdown_string(eye(3))
"$$\left( ... \right)$$"

有什么好的方法可以实现吗?在我看来,此功能必须出现在 IPython 中的某处,因为它可以在笔记本中完成。

您误解了 display_markdown() 的作用。它是不是转换表示格式的函数。 IPython 不使用 Markdown 来显示数组,在这种特定情况下它只是输出纯文本。

IPython 显示系统期望对象提供格式化的输出它们自己,markdown 只是支持的不同格式之一。因为对象可以支持 多种 格式,所以有时您希望明确地 select 一种特定格式。 display_markdown() 让你 select 降价表示并忽略其他。但是,如果一个对象没有 具有 特定的降价表示,则使用其标准 repr() 字符串作为后备。请参阅集成文档的 Rich Display section

Numpy 数组没有降价表示,因此 display_markdown() 无法使用。您看到的打印内容 只是 repr(eye(3)) 生成的字符串。所以你可以只使用 repr(eye(3)),并在降价中使用它,用反引号包裹它:

A = np.eye(3)
markdown_repr = f"```\n{A!r}\n```"

!r 语法告诉 Python 获取 repr() 的输出。以上产生字符串:

"```\narray([[1., 0., 0.],\n       [0., 1., 0.],\n       [0., 0., 1.]])\n```

如果你想在 LaTeX 中表示一个数组 ,那么有些项目确实可以生成你可以使用的 numpy 数组的这种表示;如果你将它们的结果包装在 $$ 行中,那么你可以将它们视为降价输出,因为 Jupyter 支持嵌入式 Mathjax 表达式(LaTeX 的一个子集)。

例如,使用array-to-latex:

from array_to_latex import to_ltx
to_markdown = lambda m: f"$$\n{to_ltx(m, print_out=False)}\n$$"
print(to_markdown(A))

产生

$$
\begin{bmatrix}
  1.00 &  0.00 &  0.00\
  0.00 &  1.00 &  0.00\
  0.00 &  0.00 &  1.00
\end{bmatrix}
$$

没有使用库(您可以编写自己的文本操作代码来做类似的事情),但是您不能使用IPython 做到这一点。

当然,一旦你有了这样的函数,你不仅可以直接使用它,还可以教IPython将它用于任何numpy数组。您可以将其注册为 text/markdown 和 IPython 的格式化程序,作为 third-party formatter function:

md_formatter = get_ipython().display_formatter.formatters["text/markdown"]
md_formatter.for_type(np.ndarray, to_markdown)

因为我使用的库输出 LaTeX,你可以直接使用 to_ltx()(使用 print_out=False)来生成 LaTeX 输出,这也会在你回显数组时产生 Mathjax 输出:

latex_formatter = get_ipython().display_formatter.formatters["text/latex"]
latex_formatter.for_type(np.ndarray, lambda m: to_ltx(m, print_out=False))

无论如何,现在您将看到数组的 MathJax 渲染:

现在,如果您想访问 IPython 可用的不同格式对象,那么您要使用 IPython.core.formatters.format_display_data() function;这给了你两个字典,第一个是一个以各种表示 mime 类型作为键的字典。如果对象有可用的降价转换,那么您将在 "text/markdown" 键下找到它:

from IPython.core.formatters import format_display_data
formatted, metadata = format_display_data(A)
formatted["text/markdown"]

因为我已经为 numpy 数组注册了一个 markdown 格式化程序,上面的代码为我们生成了 to_markdown() 的输出:

'$$\n\begin{bmatrix}\n  1.00 &  0.00 &  0.00\\\n  0.00 &  1.00 &  0.00\\\n  0.00 &  0.00 &  1.00\n\end{bmatrix}\n$$'

但是 如果没有 额外的丰富显示注册,您将得到的只是一个 "text/plain" 条目。