您可以使用nbformat https://nbformat.readthedocs.io/en/latest/api.html#像您指出的示例一样执行此操作。
“nbformat 包允许您以编程方式读取和解析笔记本文件。” -消息来源,托尼·赫斯特的描述 https://discourse.jupyter.org/t/is-it-possible-to-programmatically-wrap-markdown-cells/1529/2?u=fomightez
nbformat 是 Jupyter 的一部分,因此它可以在您运行笔记本的任何地方运行。
我使用 nbformat 来做与你的目标类似的事情here https://github.com/fomightez/imgs2RISEslides(处于进行中状态)。最相关的部分是here https://github.com/fomightez/imgs2RISEslides/blob/07b0a85960129c5533503aa89c469ae7253908f4/imgs2RISEslides.ipy#L259我将笔记本中单元格的元数据设置为幻灯片放映。这是该部分的要点:
import nbformat as nbf
a = nbf.v4.new_notebook()
for p in image_fn_pairs:
content_for_md_cell = slideshow_cell_stub_text.replace(
"THE_IMAGE1_PLACEHOLDER_TEXT_GOES_HERE",p[0]).replace(
"THE_IMAGE2_PLACEHOLDER_TEXT_GOES_HERE",p[1])
a.cells.append(nbf.v4.new_markdown_cell(content_for_md_cell))
# fix the metadata for each cell to be for a slide
slide_show_meta = {"slideshow": {"slide_type": "slide"}}
# a.cells = [c["metadata"] = slide_show_meta for c in a.cells]
meta_fixed_cells = []
for c in a.cells:
c["metadata"] = slide_show_meta
meta_fixed_cells.append(c)
a.cells = meta_fixed_cells
就您而言,听起来您的笔记本中已经有内容,因此在您的情况下,您需要在笔记本中阅读,首先如下所示:
import nbformat as nbf
ntbk = nbf.read("old_notebook.ipynb", nbf.NO_CONVERT)
然后像我的示例一样修复元数据。沿着这些思路:
new_ntbk = ntbk
# fix the metadata for each cell to be for a slide
slide_show_meta = {"slideshow": {"slide_type": "slide"}}
meta_fixed_cells = []
for c in ntbk.cells:
c["metadata"] = slide_show_meta
meta_fixed_cells.append(c)
new_ntbk.cells = meta_fixed_cells
nbf.write(new_ntbk, "notebook_with_slide_metadata.ipynb", version=nbf.NO_CONVERT)
您可以尝试我设置并在上面提到的自动化、正在进行的幻灯片构建过程,方法是:there https://github.com/fomightez/imgs2RISEslides并点击launch binder
。我认为,如果您只是在出现的笔记本中运行内容,它将引导您制作幻灯片,并在每张幻灯片上并排放置一些填充矩形作为图像的替代品。
您还会看到我在中使用了笔记本的存根剧本 https://github.com/fomightez/imgs2RISEslides/blob/07b0a85960129c5533503aa89c469ae7253908f4/imgs2RISEslides.ipy#L135,这是基于笔记本存根 https://github.com/fomightez/imgs2RISEslides/blob/master/RISEnb_stub.ipynb添加整个笔记本的元数据here https://github.com/fomightez/imgs2RISEslides/blob/07b0a85960129c5533503aa89c469ae7253908f4/imgs2RISEslides.ipy#L285这样当笔记本打开时就会自动播放幻灯片,即"livereveal": {"autolaunch": true, "scroll": true}
部分。
nbconvert 包含一个将编辑元数据的预处理器,请参阅here https://github.com/jupyter/nbconvert/blob/a8067447af4a90690b762f48ceb46d40207a344e/nbconvert/exporters/slides.py#L15看起来它将添加元数据。
如果您使用 JupyterLab 作为幻灯片开发工具,则可以安装 jupyterlab-deck,它将在工具栏上添加一个“deck”图标,允许您切换幻灯片查看。看用法在这里 https://github.com/deathbeds/jupyterlab-deck#usage。 (在通过 MyBinder 提供的会话的甲板模式下,如果将鼠标移向屏幕顶部,我会看到工具栏。我认为这是因为shift+esc
不起作用。或者文档还没有更新。)