Last active
June 19, 2018 15:41
-
-
Save Peng-YM/7568a885620d7b90fcd041c8bbcd10ee to your computer and use it in GitHub Desktop.
Python Script to generate markdown table of content(toc)
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
| 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() |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usages:
Ouputs will looks like: