如何通过代码将Jupyter Notebook保存到HTML?

How to save Jupyter Notebook to HTML by code?

我有一个 Jupyter Notebook 程序,可以帮我分析。变成运行后,我想保存为HTML,方便以后查看。 (然后我可以更改输入数据文件以对其他数据进行分析。)

通常,我是手工完成的。这看起来像

但这对我来说感觉很乏味。所以我想知道是否有任何代码可以为我做这件事?也许像

%save_html
# or with a file_name
%save_html file_name

注意:我已经找到解决方法。但是我没有通过搜索找到太多信息,所以我 post 在这里,它可能会帮助其他遇到同样问题的人。我会 post 我的解决方案作为答案。

您应该能够在包含 jupyter-notebook.exe 文件的同一目录中找到一个脚本。它的名字是jupyter-nbconvert.exe。 运行 像这样:

./jupyter-nbconvert.exe --to html 'path/to/nb.ipynb'`

Docs

我自己来回答

from IPython.display import Javascript
from nbconvert import HTMLExporter

def save_notebook():
    display(
        Javascript("IPython.notebook.save_notebook()"),
        include=['application/javascript']
    )

def output_HTML(read_file, output_file):
    import codecs
    import nbformat
    exporter = HTMLExporter()
    # read_file is '.ipynb', output_file is '.html'
    output_notebook = nbformat.read(read_file, as_version=4)
    output, resources = exporter.from_notebook_node(output_notebook)
    codecs.open(output_file, 'w', encoding='utf-8').write(output)

在笔记本的最后一个单元格中,类似

import time

save_notebook()
time.sleep(3)
current_file = 'GMM.ipynb'
output_file = 'output_file.html'
output_HTML(current_file, output_file)

首先打开控制台并转到笔记本所在的目录。
第二次输入此命令:

ipython nbconvert --to HTML your_notebook.ipynb

之后您将拥有名称为 "your_notebook.html" 的新文件。就这些了。

你可以查看here 获取更多信息。

如果您想要一个完全基于代码的解决方案,在笔记本中执行,您可以使用以下简短代码片段,它将为您的文件命名 'test_1':

a = 1
command = f'jupyter nbconvert Untitled.ipynb --output test_{a}.html'
subprocess.call(command)

只需执行此代码段

!!jupyter nbconvert *.ipynb