How to export and preserve linked Jupyter notebooks?

让人想犯罪 __ 提交于 2019-12-11 06:25:43

问题


I have multiple Jupyter notebooks that are linked to one another such that Notebook1.ipydb contains a link to Notebook2.ipydb with the markdown [Notebook2](Notebook2.ipynb) and vice versa.

When exporting all notebooks to HTML via nbconvert, the link to Notebook2.ipynb is preserved. I would like to change that link to the exported Notebook2.html so the linked HTML files function as a static website.

I tried to detect if I was running in iPython using get_ipython().__class__.__name__, but it executes this code before converting to HTML.

Is there a way to detect a static file to conditionally render the right markdown? Is there another way to preserve linked notebooks?


回答1:


There's only really two options. One is to link to Notebook2.html in the first place and the other is to create a custom preprocessor for 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"\[(.*)\]\(\1\.ipynb\)",r"[\1](\1.html)",cell.source)

        return cell, resources

Save this to a file, then add to your nbconvert config file (located at ~/.jupyter/jupyter_nbconvert_config.py or can be generated using the command jupyter nbconvert --generate-config) the line:

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

This assumes that the custom preprocessor file is named CustomPreprocessor and is located in the same directory as the files you're trying to convert. You could also properly install it as a module too.



来源:https://stackoverflow.com/questions/42255564/how-to-export-and-preserve-linked-jupyter-notebooks

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!