Created
June 24, 2019 08:37
-
-
Save eigenfoo/ab6e3302aab97479738202e26980969e to your computer and use it in GitHub Desktop.
Print a Markdown table of contents for a Jupyter notebook.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python | |
import argparse | |
import re | |
import json | |
import string | |
parser = argparse.ArgumentParser( | |
description="Print a Markdown table of contents for a Jupyter notebook." | |
) | |
parser.add_argument( | |
"notebook", type=str, help="Notebook for which to create table of contents." | |
) | |
args = parser.parse_args() | |
if __name__ == "__main__": | |
toc = [] | |
with open(args.notebook, "r") as f: | |
cells = json.load(f)["cells"] | |
for cell in cells: | |
if cell["cell_type"] == "markdown": | |
for line in cell["source"]: | |
match = re.search("^#+ \w+", line) | |
if match: | |
level = len(line) - len(line.lstrip("#")) | |
link = line.strip(" #\n").replace(" ", "-") | |
toc.append( | |
2 * (level - 1) * " " | |
+ "- [" | |
+ line.strip(" #\n") | |
+ "](#" | |
+ link | |
+ ")" | |
) | |
for item in toc: | |
print(item) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Exactly what I was looking for! There is a bug though that comments within formatted code in markdown cells (ie. using triple backticks) are interpretted as headings. Not a big deal though 😄