如何导出和保存链接的 Jupyter 笔记本?

How to export and preserve linked Jupyter notebooks?

我有多个 Jupyter notebooks,它们相互 linked 到 Notebook1.ipydb 包含一个 link 到 Notebook2.ipydb 与降价 [Notebook2](Notebook2.ipynb) 反之亦然。

当通过 nbconvert 将所有笔记本导出到 HTML 时,link 到 Notebook2.ipynb 被保留。我想将 link 更改为导出的 Notebook2.html,以便 linked HTML 文件用作静态网站。

我尝试使用 get_ipython().__class__.__name__ 检测我是否在 iPython 中 运行,但它在 转换为 之前执行此代码35=]。

有没有办法检测静态文件以有条件地呈现正确的降价?还有其他方法可以保存 linked 笔记本吗?

真的只有两个选择。一个是首先 link 到 Notebook2.html,另一个是为 nbconvert 创建自定义预处理器。

from nbconvert.preprocessors import Preprocessor
import re


class CustomPreprocessor(Preprocessor):

    def preprocess_cell(self, cell, resources, index):

        if 'source' in cell and cell.cell_type == "markdown":
            cell.source = re.sub(r"\[(.*)\]\(\.ipynb\)",r"[](.html)",cell.source)

        return cell, resources

将其保存到文件中,然后将以下行添加到您的 nbconvert 配置文件(位于 ~/.jupyter/jupyter_nbconvert_config.py 或可以使用命令 jupyter nbconvert --generate-config 生成):

c.HTMLExporter.preprocessors = ['CustomPreprocessor.CustomPreprocessor']

这假定自定义预处理器文件名为 CustomPreprocessor 并且位于与您要转换的文件相同的目录中。您也可以将其作为模块正确安装。