To be run in Jupyter to generate ../exercises/*.ipynb
from ./*.ipynb
In [4]:
import json, os, re
from IPython.core.display import display, HTML
In [5]:
def convert(code):
converted = []
for line in code:
assert 'todo' not in line.lower()
m = re.match('^\s*(?:#|//|<!-- )--snip', line)
if m:
break
m = re.match(r'^(\s*)(.*?)\s+(?:#|//)([^ @].*)$', line)
converted.append((m.group(1) + m.group(3) + '\n') if m else line)
return converted
In [6]:
SOURCE = '.'
DESTINATION = '../exercises'
NOTE_FMT = '### NOTE: This file is auto-generated from "%s".\n\n'
LINK_FMT = ('<li><a target="_blank" href="%s">%s</a> (%d bytes) ⇨ '
'<a target="_blank" href="%s">%s</a> (%d bytes)</li>')
if not os.path.exists(DESTINATION):
os.mkdir(DESTINATION)
display(HTML('<pre>'))
for name in sorted(os.listdir(SOURCE)):
if not name.endswith('.ipynb') or name.startswith('_'):
continue
path = os.path.join(SOURCE, name)
nb = json.load(open(path))
for cell in nb['cells']:
if cell['cell_type'] == 'code':
cell['source'] = convert(cell['source'])
if 'outputs' in cell: cell['outputs'] = []
if 'execution_count' in cell: cell['execution_count'] = None
# nb['cells'][0]['source'].insert(0, NOTE_FMT % os.path.abspath(path))
path2 = os.path.join(DESTINATION, name)
json.dump(nb, open(path2, 'w'))
display(HTML(LINK_FMT % (path, path, os.path.getsize(path),
path2, path2, os.path.getsize(path2))))