如何正确合并两个ipython笔记本而不会出现json错误? [英] How to merge two ipython notebooks correctly without getting json error?

查看:205
本文介绍了如何正确合并两个ipython笔记本而不会出现json错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过:

cat file1.ipynb file2.ipynb > filecomplete.ipynb 

由于笔记本只是json文件,但这给了我错误

since the notebooks are simply json files, but this gives me the error

Unreadable Notebook: Notebook does not appear to be JSON: '{\n "metadata": {'

我认为这些文件必须是有效的json文件,因为file1和file2分别分别加载到nbviewer中,因此我不完全确定自己做错了什么.

I think these must be valid json files because file1 and file2 each load individually into nbviewer, and so I am not entirely sure what I am doing wrong.

推荐答案

此Python脚本将所有以给定prefix命名并出现在给定folder的第一层的笔记本串联在一起.生成的笔记本将保存在同一文件夹下,名称为"compil_" + prefix + ".ipynb".

This Python script concatenates all the notebooks named with a given prefix and present at the first level of a given folder. The resulting notebook is saved in the same folder under the name "compil_" + prefix + ".ipynb".

import json
import os

folder = "slides"
prefix = "quiz"
paths = [os.path.join(folder, name) for name in os.listdir(folder) if name.startswith(prefix) and name.endswith(".ipynb")]
result = json.loads(open(paths.pop(0), "r").read())
for path in paths:
    result["worksheets"][0]["cells"].extend(json.loads(open(path, "r").read())["worksheets"][0]["cells"])
open(os.path.join(folder, "compil_%s.ipynb" % prefix), "w").write(json.dumps(result, indent = 1))

警告:元数据仅是第一个笔记本的元数据,而单元格仅是第一个工作表的元数据(至少在我的笔记本中似乎包含所有单元格).

Warning: the metadata are those of the first notebook, and the cells those of the first worksheet only (which seems to contain all the cells, in my notebook at least).

这篇关于如何正确合并两个ipython笔记本而不会出现json错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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