【问题标题】:Convert a Jupyter notebook to html output in native Python在本机 Python 中将 Jupyter 笔记本转换为 html 输出
【发布时间】:2020-12-30 04:26:07
【问题描述】:

我知道我可以打电话

jupyter nbconvert --execute --to html notebook.ipynb

从 shell,或从 Python 进行系统调用:

import os
os.system('jupyter nbconvert --execute --to html notebook.ipynb')

但是当 nbconvert 模块在原生 Python 中可用时,必须通过系统调用来执行此操作似乎很奇怪!

我想编写原生 python 来执行 iPython 笔记本并将其转换为 html 文件。 我研究了official documentation 一点,但无法拼凑起来。 我的问题是:

  1. 有没有在本机 Python 中将笔记本转换为 html 的示例?
  2. 是否有令人信服的理由不这样做?

【问题讨论】:

    标签: jupyter-notebook jupyter nbconvert


    【解决方案1】:

    好的,经过反复试验,我想通了:

    import nbformat
    from nbconvert.preprocessors import ExecutePreprocessor
    from nbconvert import HTMLExporter
    
    # read source notebook
    with open('report.ipynb') as f:
        nb = nbformat.read(f, as_version=4)
    
    # execute notebook
    ep = ExecutePreprocessor(timeout=-1, kernel_name='python3')
    ep.preprocess(nb)
    
    # export to html
    html_exporter = HTMLExporter()
    html_exporter.exclude_input = True
    html_data, resources = html_exporter.from_notebook_node(nb)
    
    # write to output file
    with open("notebook.html", "w") as f:
        f.write(html_data)
    

    诚然,这比单个 os.system 调用要多得多,但我很惊讶那里的原生 python 示例如此之少......

    【讨论】:

    • 我必须将 HTML 文件的编码设置为 UTF-8:“with open("output/MEB_SKI_26_analysis.html", "w", encoding="utf") as f:"
    猜你喜欢
    • 2015-05-12
    • 1970-01-01
    • 2022-10-02
    • 2018-01-22
    • 2015-12-10
    • 2017-03-21
    • 2019-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多