格式化代码输出#
代码输出的格式高度可配置。下面我们给出如何格式化特定输出的示例,甚至将输出插入到文档的其他位置。
See also
MyST-NB 文档,了解如何完全自定义输出渲染器。
库的输出格式化#
许多库支持它们自己的 HTML 输出格式化,这通常也适用于 Jupyter Book 的输出。
例如,以下单元格使用 Pandas 根据单元格的值来格式化单元格:
Show code cell source
import numpy as np
import pandas as pd
np.random.seed(24)
df = pd.DataFrame({'A': np.linspace(1, 10, 10)})
df = pd.concat([df, pd.DataFrame(np.random.randn(10, 4), columns=list('BCDE'))],
axis=1)
df.iloc[3, 3] = np.nan
df.iloc[0, 2] = np.nan
def color_negative_red(val):
"""
Takes a scalar and returns a string with
the css property `'color: red'` for negative
strings, black otherwise.
"""
color = 'red' if val < 0 else 'black'
return 'color: %s' % color
def highlight_max(s):
'''
highlight the maximum in a Series yellow.
'''
is_max = s == s.max()
return ['background-color: yellow' if v else '' for v in is_max]
df.style.\
applymap(color_negative_red).\
apply(highlight_max).\
set_table_attributes('style="font-size: 10px"')
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
Cell In[1], line 1
----> 1 import numpy as np
2 import pandas as pd
4 np.random.seed(24)
ModuleNotFoundError: No module named 'numpy'
有关样式化 DataFrame 的更多信息,请参阅 Pandas 样式化文档,并查看您选择的库的文档,看看它们是否支持类似的功能。
滚动单元格输出#
传统的 Jupyter Notebook 界面允许您为单元格切换输出滚动。这使您能够可视化部分长输出,而不会占用整个页面。
您可以通过向单元格的元数据添加以下标签来在 Jupyter Book 中触发此行为:
{
"tags": [
"scroll-output",
]
}
例如,以下单元格有一个长输出,但在书中将是可滚动的:
for ii in range(40):
print(f"this is output line {ii}")
this is output line 0
this is output line 1
this is output line 2
this is output line 3
this is output line 4
this is output line 5
this is output line 6
this is output line 7
this is output line 8
this is output line 9
this is output line 10
this is output line 11
this is output line 12
this is output line 13
this is output line 14
this is output line 15
this is output line 16
this is output line 17
this is output line 18
this is output line 19
this is output line 20
this is output line 21
this is output line 22
this is output line 23
this is output line 24
this is output line 25
this is output line 26
this is output line 27
this is output line 28
this is output line 29
this is output line 30
this is output line 31
this is output line 32
this is output line 33
this is output line 34
this is output line 35
this is output line 36
this is output line 37
this is output line 38
this is output line 39
在编写 MyST markdown 文档时,您可以使用 :tags: ["scroll-output"] 作为 code-cell 指令的选项,例如:
```{code-cell} ipython3
:tags: [scroll-output]
for ii in range(40):
print(f"this is output line {ii}")
```
图片#
对于代码输出的任何图像类型,我们可以通过单元格元数据应用格式化。然后对于图像,我们可以应用标准 图像指令 的所有变量:
width: 长度或当前行宽度的百分比(%)
height: 长度
scale: 整数百分比(可选 “%” 符号)
align: “top”, “middle”, “bottom”, “left”, “center”, 或 “right”
classes: 空格分隔的字符串
alt: 字符串
我们还可以设置一个标题(渲染为 CommonMark)和一个引用图形的名称。代码
```{code-cell} ipython3
---
mystnb:
image:
width: 200px
alt: fun-fish
classes: shadow bg-primary
figure:
caption: |
Hey everyone its **party** time!
name: fun-fish
---
from IPython.display import Image
Image("../images/fun-fish.png")
```
生成以下代码单元格和图形:
from IPython.display import Image
Image("../images/fun-fish.png")
Fig. 11 Hey everyone its party time!#
现在我们可以从文档的任何地方链接到图像:swim to the fish
See also
Markdown#
Markdown 输出由 MyST-Parser 解析,目前解析设置为严格 CommonMark。
解析后的 Markdown 随后被整合到文档的更广泛上下文中。这意味着,例如,可以包含内部引用:
from IPython.display import display, Markdown
display(Markdown('**_some_ markdown** and an [internal reference](render/output/markdown)!'))
some markdown and an internal reference!
甚至内部图像也可以渲染,如下面的代码示例所示:
display(Markdown(''))
ANSI 输出#
默认情况下,标准输出/错误流和文本/纯文本 MIME 输出可能包含 ANSI 转义序列,以改变文本和背景颜色。
import sys
print("BEWARE: \x1b[1;33;41mugly colors\x1b[m!", file=sys.stderr)
print("AB\x1b[43mCD\x1b[35mEF\x1b[1mGH\x1b[4mIJ\x1b[7m"
"KL\x1b[49mMN\x1b[39mOP\x1b[22mQR\x1b[24mST\x1b[27mUV")
ABCDEFGHIJKLMNOPQRSTUV
这使用了内置的 AnsiColorLexer pygments 词法分析器。你可以在 _config.yml 中更改使用的词法分析器,例如关闭词法分析:
sphinx:
config:
nb_render_text_lexer: "none"
以下代码展示了它基于的 8 种基本 ANSI 颜色。每种颜色都有一个“强烈”变体,用于粗体文本。
text = " XYZ "
formatstring = "\x1b[{}m" + text + "\x1b[m"
print(
" " * 6
+ " " * len(text)
+ "".join("{:^{}}".format(bg, len(text)) for bg in range(40, 48))
)
for fg in range(30, 38):
for bold in False, True:
fg_code = ("1;" if bold else "") + str(fg)
print(
" {:>4} ".format(fg_code)
+ formatstring.format(fg_code)
+ "".join(
formatstring.format(fg_code + ";" + str(bg)) for bg in range(40, 48)
)
)
40 41 42 43 44 45 46 47
30 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;30 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
31 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;31 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
32 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;32 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
33 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;33 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
34 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;34 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
35 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;35 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
36 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;36 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
37 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
1;37 XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ XYZ
Note
ANSI 还支持一组 256 种索引颜色。 目前尚不支持这一点,但我们希望在未来的某个时候引入它(如果你需要它,请在仓库中提出问题!)。
渲染优先级#
当 Jupyter 执行一个代码单元时,它可以产生多个输出,并且每个输出可以包含多个 MIME 媒体类型,以便用于不同的输出格式(如 HTML 或 LaTeX)。
MyST-NB 为大多数常见的 输出构建器 存储了一个默认优先级字典,你也可以在 _config.yml 中更新它。例如,这是 HTML 的默认优先级列表:
sphinx:
config:
nb_mime_priority_overrides: [
['html', 'application/vnd.jupyter.widget-view+json', 10],
['html', 'application/javascript', 20],
['html', 'text/html', 30],
['html', 'image/svg+xml', 40],
['html', 'image/png', 50],
['html', 'image/gif', 60],
['html', 'image/jpeg', 70],
['html', 'text/markdown', 80],
['html', 'text/latex', 90],
['html', 'text/plain', 100]
]