【问题标题】:Run preprocessor using nbconvert as a library使用 nbconvert 作为库运行预处理器
【发布时间】: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


    【解决方案1】:

    对于您的特殊情况,我相信您可以通过更改来解决问题:c.RemovePreprocessor.remove_cell_tags = ('skip',) -> c.<strong>Tag</strong>RemovePreprocessor.remove_cell_tags = ('skip',)


    为了其他人的利益,就像我通过搜索一样遇到这个线程

    ModuleNotFoundError: No module named 'TagRemovePreprocessor'
    

    open issueTagRemovePreprocessor 会导致除 HTMLExporter(和 LatexExporter?)之外的所有导出器自动禁用此预处理器。

    在我的例子中,我尝试使用 NotebookExporter 并需要显式启用预处理器并更改预处理级别,如下所示:

    import json
    from traitlets.config import Config
    from nbconvert import NotebookExporter
    import nbformat
    
    c = Config()
    c.TagRemovePreprocessor.enabled=True # Add line to enable the preprocessor
    c.TagRemovePreprocessor.remove_cell_tags = ["del_cell"]
    c.preprocessors = ['TagRemovePreprocessor'] # Was previously: c.NotebookExporter.preprocessors
    
    nb_body, resources = NotebookExporter(config=c).from_filename('notebook.ipynb')
    nbformat.write(nbformat.from_dict(json.loads(nb_body)),'stripped_notebook.ipynb',4)
    

    【讨论】:

    • 谢谢。我还必须将c.LatexExporter.preprocessors 更改为c.preprocessors,如您的示例所示。
    • 您甚至可以对删除标记单元格的同一笔记本执行此操作(此处:“del_cell”)!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 2013-03-06
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多