forked from MonashDataFluency/python-workshop-base
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown2ipynb.py
More file actions
executable file
·81 lines (73 loc) · 2.07 KB
/
markdown2ipynb.py
File metadata and controls
executable file
·81 lines (73 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
# Hacky script to take Markdown with ```python code blocks
# and convert to a ipynb format Jupyter notebook.
# The result will almost always need hand editing in Jupyter after
# conversion.
#
# Usage:
#
# python markdown2ipynb.py some_markdown.md >a_notebook.ipynb
import sys
import json
with open(sys.argv[1], 'r') as f:
content = f.readlines()
metadata = {
"metadata": {
"celltoolbar": "Tags",
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
cells = {"cells": []}
split_at_markdown_h2 = True
in_python_block = False
source = []
for line in content:
if line.startswith("```python"):
in_python_block = True
# source_lines = ["%s\n" % l for l in source]
cells['cells'].append(
{"cell_type": "markdown",
"metadata": {},
"source": list(source)})
source = []
continue
if in_python_block and line.startswith("```"):
in_python_block = False
cells['cells'].append(
{"cell_type": "code",
"metadata": {},
"outputs": [],
"execution_count": 0,
"source": list(source)})
source = []
continue
if not in_python_block:
if split_at_markdown_h2 and line.startswith("## "):
cells['cells'].append(
{"cell_type": "markdown",
"metadata": {},
"source": list(source)})
source = []
source.append(line)
continue
source.append(line)
cells.update(metadata)
print(json.dumps(cells, indent=2))