IPython notebook:将HTML笔记本转换为ipynb

fog*_*rit 24 python ipython jupyter jupyter-notebook nbconvert

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

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

sgD*_*ion 19

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

这是我的代码

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))
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

  • 那很棒.感谢分享. (4认同)
  • 奇迹般有效!我只需要安装`lxml`(`pip install lxml`)并创建ipynb! (2认同)
  • ❤️额外的基本操作步骤 1. 创建一个新文件 `intonotebook.py` 打开代码编辑器(不是在 Word 中) 2. 复制粘贴此答案中的第一段代码。3. 将顶行 4 更改为您的文件 web。但如果文件在您的计算机上,请将 # 放在第 4 行和第 5 行前面,并在第 7 行之前删除 #。然后将第 7 行更改为您的 html 文件所在的位置(# 表示“注释”)。确保您编辑的行的开头没有空格。保存文件。4. 打开终端,转到您创建文件的文件夹并输入“python intonotebook.py”。5. 要更改输出文件的名称,请更改最后一行 (2认同)