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

时间:2016-06-06 12:30:06

标签: jupyter-notebook

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

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

enter image description here

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

%save_html
# or with a file_name
%save_html file_name

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

5 个答案:

答案 0 :(得分:7)

我自己会给出答案。

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

def output_HTML(read_file, output_file):
    from nbconvert import HTMLExporter
    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)

答案 1 :(得分:3)

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

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

Docs

答案 2 :(得分:1)

首先打开控制台,然后转到笔记本所在的目录 第二个输入此命令:

ipython nbconvert --to HTML your_notebook.ipynb

之后,您将获得名为“your_notebook.html”的新文件。多数民众赞成。

您可以查看here 了解更多信息。

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

只需执行此代码段

!!jupyter nbconvert *.ipynb