Jupyter(IPython)笔记本:将HTML笔记本转换为ipynb [英] Jupyter (IPython) notebook: Convert an HTML notebook to ipynb

查看:203
本文介绍了Jupyter(IPython)笔记本:将HTML笔记本转换为ipynb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将Jupyter/IPython笔记本转换为HTML格式,随后丢失了原始ipynb文件.

I have converted a Jupyter/IPython notebook to HTML format and subsequently lost the original ipynb file.

是否有一种简单的方法可以从转换后的HTML文件生成原始笔记本文件?

Is there a simple way to generate the original notebook file from the converted HTML file?

推荐答案

我最近使用BeautifulSoup和JSON将html笔记本转换为ipynb.诀窍是查看笔记本的JSON模式并对其进行仿真.该代码仅选择输入代码单元格和降价单元格

I recently used BeautifulSoup and JSON to convert html notebook to ipynb. the trick is to look at the JSON schema of a notebook and emulate that. The code selects only input code cells and markdown cells

这是我的代码

from bs4 import BeautifulSoup
import json
import urllib.request
url = 'http://nbviewer.jupyter.org/url/jakevdp.github.com/downloads/notebooks/XKCD_plots.ipynb'
response = urllib.request.urlopen(url)
#  for local html file
# response = open("/Users/note/jupyter/notebook.html")
text = response.read()

soup = BeautifulSoup(text, 'lxml')
# see some of the html
print(soup.div)
dictionary = {'nbformat': 4, 'nbformat_minor': 1, 'cells': [], 'metadata': {}}
for d in soup.findAll("div"):
    if 'class' in d.attrs.keys():
        for clas in d.attrs["class"]:
            if clas in ["text_cell_render", "input_area"]:
                # code cell
                if clas == "input_area":
                    cell = {}
                    cell['metadata'] = {}
                    cell['outputs'] = []
                    cell['source'] = [d.get_text()]
                    cell['execution_count'] = None
                    cell['cell_type'] = 'code'
                    dictionary['cells'].append(cell)

                else:
                    cell = {}
                    cell['metadata'] = {}

                    cell['source'] = [d.decode_contents()]
                    cell['cell_type'] = 'markdown'
                    dictionary['cells'].append(cell)
open('notebook.ipynb', 'w').write(json.dumps(dictionary))

这是print(soup.div)输出的一部分

div class="container">
<div class="navbar-header">
<button class="navbar-toggle collapsed" data-target=".navbar-collapse" data-toggle="collapse" type="button">
<span class="sr-only">Toggle navigation</span>
<i class="fa fa-bars"></i>
</button>
<a class="navbar-brand" href="/">
<img src="/static/img/nav_logo.svg?v=479cefe8d932fb14a67b93911b97d70f" width="159"/>
</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav navbar-right">
<li>
<a class="active" href="http://jupyter.org">JUPYTER</a>
</li>
<li>
<a href="/faq" title="FAQ">
<span>FAQ</span>

生成的ipynb文件的屏幕截图,已在运行所有单元格后加载到我的本地jupyter中

A screen shot of the resulting ipynb file, loaded on my local jupyter and after running all the cells

这篇关于Jupyter(IPython)笔记本:将HTML笔记本转换为ipynb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆