-
Notifications
You must be signed in to change notification settings - Fork 14
/
convert.py
53 lines (41 loc) · 1.58 KB
/
convert.py
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
"""Convert Octave notebooks to scripts."""
from __future__ import annotations
import json
from pathlib import Path
from rich import print
this_dir = Path(__file__).parent
notebooks = this_dir.glob("**/*.ipynb")
for ntbk in notebooks:
print(ntbk)
with open(ntbk) as f:
nb = json.load(f)
filename = ntbk.stem.replace("-", "_")
output_file = ntbk.with_stem(filename).with_suffix(".m")
with open(output_file, "w") as f:
for cell in nb["cells"]:
if cell["cell_type"] == "markdown":
for i, line in enumerate(cell["source"]):
line = line.rstrip()
ending = "\n"
if i == len(cell["source"]) - 1:
ending = ""
if line == "":
print("%", file=f)
else:
print(f"% {line.rstrip()}{ending}", file=f, end="")
if cell["cell_type"] == "code":
for i, line in enumerate(cell["source"]):
line = line.rstrip()
ending = "\n"
if i == len(cell["source"]) - 1:
ending = ""
if line == "":
print("", file=f)
elif not line.endswith(";") and not line.endswith("..."):
print(f"{line.rstrip()};{ending}", file=f, end="")
else:
print(f"{line.rstrip()}{ending}", file=f, end="")
print(
"\n",
file=f,
)