我想使用预处理器运行 nbconvert,该预处理器会删除标有“skip”标签的单元格。我可以从命令行执行此操作,但是当我尝试在笔记本中使用 nbconvert API 时,我遇到了问题。
一个例子
按照中的示例文档 https://nbconvert.readthedocs.io/en/latest/nbconvert_library.html#Quick-overview,我拿了一个笔记本来工作。
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]{arti
再说一遍,没问题。转换正在进行中。
现在,尝试使用我在命令行中使用的相同预处理器:
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”的模块
据我所知,这段代码与文档中的代码示例 https://nbconvert.readthedocs.io/en/latest/removing_cells.html#removing-pieces-of-cells-using-cell-tags,除了我使用的是 Latex 导出器而不是 HTML。那么为什么它不起作用呢?