Skip to content

Instantly share code, notes, and snippets.

@Peng-YM
Last active June 19, 2018 15:41
Show Gist options
  • Select an option

  • Save Peng-YM/7568a885620d7b90fcd041c8bbcd10ee to your computer and use it in GitHub Desktop.

Select an option

Save Peng-YM/7568a885620d7b90fcd041c8bbcd10ee to your computer and use it in GitHub Desktop.
Python Script to generate markdown table of content(toc)
import argparse
from typing import Tuple, List
class TOC(object):
def __init__(self, path: str) -> None:
self._path = path
self._buffer: List[str] = []
def add_toc(self):
self._buffer.append("Table of Content")
self._buffer.append('='*20)
with open(self._path, 'r') as f:
for line in f.readlines():
level, title = self._get_title(line)
if level > 0:
self._buffer.append(' ' * (level-1) +
f"* [{title}](#{title})")
print('\n'.join(self._buffer))
def _get_title(self, line: str) -> Tuple[int, str]:
level = 0
for c in line:
if c == '#':
level += 1
else:
break
title = line[level+1:-1]
return (level, title)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
# parse arguments
parser.add_argument('path', type=str, help="markdown path")
args = parser.parse_args()
# add toc
toc = TOC(args.path, args.trigger)
toc.add_toc()
@Peng-YM
Copy link
Author

Peng-YM commented Jun 19, 2018

Example usages:

$ python3 toc.py something.md

Ouputs will looks like:

Table of Content
====================
* [Title](#Title)
    * [1](#1)
        * [1.1](#1.1)
            * [1.1.1](#1.1.1)
    * [2](#2)
        * [2.1](#2.1)
        * [2.2](#2.2)

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