Skip to content

Commit f5c6f0c

Browse files
committed
Adding conversion tool.
1 parent bcd7b3b commit f5c6f0c

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

tools/convert_nbformat.py

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
2+
import re
3+
import json
4+
import os
5+
import sys
6+
import os.path as op
7+
8+
from IPython.nbformat import read, convert, write, validate
9+
10+
def get_chapter_number(dir):
11+
return int(op.basename(dir)[7:9])
12+
13+
def get_chapter_name(number):
14+
return CHAPTER_NAMES[number-1]
15+
16+
def iter_chapters(root):
17+
for chapter in sorted([_ for _ in os.listdir(root)
18+
if _.startswith('chapter')]):
19+
yield chapter
20+
21+
def iter_recipes(root, dir):
22+
files = sorted([_ for _ in os.listdir(op.join(root, dir))
23+
if re.match(r'\d{2}\_[^.]+\.ipynb', _)])
24+
for file in files:
25+
yield file
26+
27+
curdir = op.realpath(op.dirname(os.path.abspath(__file__)))
28+
root = op.realpath(op.join(curdir, '../notebooks'))
29+
30+
def convert_to_v4(path):
31+
nb = read(path, 3)
32+
nb_new = convert(nb, 4)
33+
34+
for cell in nb_new['cells']:
35+
if cell.get('metadata', {}) == []:
36+
cell['metadata'] = {}
37+
38+
nb_new["metadata"] ={
39+
"kernelspec": {
40+
"display_name": "Python 3",
41+
"language": "python",
42+
"name": "python3"
43+
},
44+
"language_info": {
45+
"codemirror_mode": {
46+
"name": "ipython",
47+
"version": 3
48+
},
49+
"file_extension": ".py",
50+
"mimetype": "text/x-python",
51+
"name": "python",
52+
"nbconvert_exporter": "python",
53+
"pygments_lexer": "ipython3",
54+
"version": "3.4.2"
55+
}
56+
}
57+
58+
validate(nb_new)
59+
write(nb_new, path)
60+
61+
if __name__ == '__main__':
62+
63+
for chapter in iter_chapters(root):
64+
for recipe in iter_recipes(root, chapter):
65+
file = op.join(root, chapter, recipe)
66+
67+
if recipe in ('01_notebook.ipynb',
68+
'02_pandas.ipynb',
69+
'03_numpy.ipynb',):
70+
continue
71+
print("converting", file)
72+
convert_to_v4(file)

0 commit comments

Comments
 (0)