如何在Colab Notebook中自动生成无编号目录?
Great question—long Colab notebooks with nested headings can get messy fast, and a manual TOC is both tedious and error-prone. Unfortunately, Colab doesn’t have a one-click "Insert TOC" feature like Google Docs, but there are two excellent auto-generated solutions that fit your needs perfectly:
1. Use Colab's Built-in Outline Panel (Quickest Option)
This is the simplest, no-code way to navigate your notebook, and it’s auto-updated as you edit headings. Here’s how to access it:
- If the left sidebar is hidden, click the hamburger menu (☰) at the top-left corner of Colab to reveal it.
- Click the Outline icon (looks like a bulleted list, next to the file explorer icon).
- The panel will instantly populate with all your
#,##, and###headings, nested correctly to match your structure. - Click any entry to jump directly to that section—no manual linking required.
- Bonus: The outline updates automatically whenever you add, edit, or delete a heading.
2. Generate an Inline Clickable TOC with Code
If you want a visible, clickable TOC directly within your notebook (e.g., at the top), you can run a script that scans your notebook’s cells and generates a markdown TOC automatically. This eliminates all manual work and ensures accuracy.
Here’s a reliable script to use:
import json from IPython.display import Markdown # Load the notebook's underlying JSON structure (synced by Colab when saved) with open('/content/notebook.ipynb', 'r') as f: notebook_data = json.load(f) toc_entries = [] for cell in notebook_data['cells']: if cell['cell_type'] == 'markdown': for line in cell['source']: # Detect headings (supports #, ##, ### levels) if line.startswith('#'): heading_level = line.count('#') heading_title = line.strip('# ').strip() # Create a URL-friendly slug for linking slug = heading_title.lower().replace(' ', '-').replace(':', '').replace('?', '').replace('!', '') # Build nested TOC line toc_line = f"{' '*(heading_level-1)}- [{heading_title}](#{slug})" toc_entries.append(toc_line) # Display the generated TOC as clickable markdown Markdown('\n'.join(toc_entries))
How to use this:
- Create a new code cell at the location where you want the TOC to appear (usually the top of the notebook).
- Paste the code above and run the cell.
- The output will be a nested, clickable markdown TOC that links directly to each heading.
- If you update your headings later, just re-run the code to refresh the TOC—no manual edits needed.
Pro tip:
If you want to convert the dynamic TOC output to a static markdown cell (so it persists without re-running the code), right-click the output and select "Save as Markdown Cell". Just remember to re-run the script if you modify your headings afterward.
内容的提问来源于stack exchange,提问作者stevec

