Skip to content

Instantly share code, notes, and snippets.

@eigenfoo
Created June 24, 2019 08:37
Show Gist options
  • Save eigenfoo/ab6e3302aab97479738202e26980969e to your computer and use it in GitHub Desktop.
Save eigenfoo/ab6e3302aab97479738202e26980969e to your computer and use it in GitHub Desktop.
Print a Markdown table of contents for a Jupyter notebook.
#!/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)
@shahrokh-bahtooei
Copy link

Dear George,

Would you be able to let me know what license this code is under? I'd like to fork it so that it'll generate a numbered list for Contents.

Thanks!

@eigenfoo
Copy link
Author

Hello! Not sure how to properly license a gist, but please feel free to use it 😃

@shahrokh-bahtooei
Copy link

Thanks a million!

Jeff Luszcz sheds good light on this issue in the blog post Getting the Gist of GitHub Gist Licensing:

The most helpful and accurate way for a Gist author to declare their license is to put the license text in the source on the Gist itself. Typically this would be at the top of the file in a comment block and would contain the copyright date and owner if required by the license.

@VeckoTheGecko
Copy link

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 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment