【发布时间】:2019-10-25 19:07:18
【问题描述】:
我想使用预处理器运行 nbconvert,该预处理器删除标有“跳过”标签的单元格。我可以从命令行执行此操作,但是当我尝试在笔记本中使用 nbconvert API 时遇到问题。
一个例子
按照documentation 中的示例,我得到了一个可以使用的笔记本。
from urllib.request import urlopen
url = 'http://jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb'
response = urlopen(url).read().decode()
import nbformat
nb = nbformat.reads(response, as_version=4)
我将修改一个单元格,使其在输出中被跳过。
nb.cells[1].metadata = {'tags': ['skip']}
命令行
保存文件,然后从命令行运行 nbconvert:
nbformat.write(nb, 'nb.ipynb')
%%bash
jupyter nbconvert --to latex \
--TagRemovePreprocessor.remove_cell_tags='{"skip"}' \
--TagRemovePreprocessor.enabled=True \
'nb.ipynb'
这行得通。输出nb.tex 文件不包含标记为“skip”的单元格。
API
现在让我们改用 API 来尝试一下。首先,无需任何预处理:
import nbconvert
latex, _ = LatexExporter().from_notebook_node(nb)
print(latex[:25])
\documentclass[11pt]{艺术家
同样,没问题。转换正在运行。
现在,尝试使用我在命令行中使用的相同预处理器:
from traitlets.config import Config
c = Config()
c.RemovePreprocessor.remove_cell_tags = ('skip',)
c.LatexExporter.preprocessors = ['TagRemovePreprocessor']
LatexExporter(config=c).from_notebook_node(nb)
这一次,我明白了:
ModuleNotFoundError: 没有名为“TagRemovePreprocessor”的模块
据我所知,此代码与code sample in the documentation 匹配,只是我使用的是 Latex 导出器而不是 HTML。那么为什么它不起作用呢?
【问题讨论】:
标签: jupyter-notebook nbconvert