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

cqc*_*991 3 jupyter-notebook

我有一个Jupyter Notebook程序,它为我做分析.在运行之后,我想将其保存为HTML,以便稍后查看.(然后我可以更改输入数据文件以对其他数据进行分析.)

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

在此输入图像描述

但这对我来说非常乏味.所以我想知道是否有任何代码可以为我做这个?也许是这样的

%save_html
# or with a file_name
%save_html file_name
Run Code Online (Sandbox Code Playgroud)

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

cqc*_*991 9

我会给自己一个答案.

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)

Run Code Online (Sandbox Code Playgroud)

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

import time

save_notebook()
time.sleep(3)
current_file = 'GMM.ipynb'
output_file = 'output_file.html'
output_HTML(current_file, output_file)
Run Code Online (Sandbox Code Playgroud)

  • 你忘了在save_notebook()之前从Ipython.display导入Javascript (2认同)

piR*_*red 6

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

./jupyter-nbconvert.exe --to html 'path/to/nb.ipynb'`
Run Code Online (Sandbox Code Playgroud)

文档