|
1 | 1 | import os
|
2 | 2 | import re
|
3 | 3 | import itertools
|
4 |
| - |
5 |
| -PREV_TEMPLATE = " <[{title}]({url}) " |
6 |
| -CONTENTS = "| [Contents](Index.ipynb)| " |
7 |
| -NEXT_TEMPLATE = " [{title}](url) >" |
| 4 | +import nbformat |
8 | 5 |
|
9 | 6 | NOTEBOOK_DIR = os.path.join(os.path.dirname(__file__), '..', 'notebooks')
|
10 | 7 |
|
|
17 | 14 |
|
18 | 15 | REG = re.compile(r'(\d\d)\.(\d\d)-(.*)\.ipynb')
|
19 | 16 |
|
20 |
| -notebooks = sorted(nb for nb in os.listdir(NOTEBOOK_DIR) if REG.match(nb)) |
21 |
| - |
22 |
| -def prev_this_next(it): |
23 |
| - a, b, c = itertools.tee(it,3) |
24 |
| - next(c) |
25 |
| - return zip(itertools.chain([None], a), b, itertools.chain(c, [None])) |
26 |
| - |
27 | 17 |
|
| 18 | +def iter_notebooks(): |
| 19 | + return sorted(nb for nb in os.listdir(NOTEBOOK_DIR) if REG.match(nb)) |
28 | 20 |
|
29 | 21 |
|
30 |
| -def iter_navbars(notebooks): |
31 |
| - for prev_nb, nb, next_nb in prev_this_next(notebooks): |
32 |
| - navbar = "" |
33 |
| - if prev_nb: |
34 |
| - navbar += PREV_TEMPLATE.format(title=REG.match(prev_nb).groups()[2], |
35 |
| - url=prev_nb) |
36 |
| - navbar += CONTENTS |
37 |
| - if next_nb: |
38 |
| - navbar += NEXT_TEMPLATE.format(title=REG.match(next_nb).groups()[2], |
39 |
| - url=next_nb) |
40 |
| - yield navbar |
| 22 | +def get_notebook_title(nb_file): |
| 23 | + nb = nbformat.read(os.path.join(NOTEBOOK_DIR, nb_file), as_version=4) |
| 24 | + for cell in nb.cells: |
| 25 | + if cell.source.startswith('#'): |
| 26 | + return cell.source[1:].splitlines()[0].strip() |
41 | 27 |
|
42 | 28 |
|
43 |
| -def gen_contents(notebooks): |
44 |
| - def get_chapter(nb): |
45 |
| - return REG.match(nb).groups()[0] |
46 |
| - |
47 |
| - for nb in notebooks: |
| 29 | +def gen_contents(directory=None): |
| 30 | + for nb in iter_notebooks(): |
| 31 | + if directory: |
| 32 | + nb_url = os.path.join(directory, nb) |
| 33 | + else: |
| 34 | + nb_url = nb |
48 | 35 | chapter, section, title = REG.match(nb).groups()
|
49 |
| - title = title.replace('-', ' ') |
| 36 | + title = get_notebook_title(nb) |
50 | 37 | if section == '00':
|
51 |
| - yield '\n### [{0}]({1})'.format(title, nb) |
| 38 | + yield '\n### [{0}]({1})'.format(title, nb_url) |
52 | 39 | else:
|
53 |
| - yield "- [{0}]({1})".format(title, nb) |
| 40 | + yield "- [{0}]({1})".format(title, nb_url) |
| 41 | + |
| 42 | + |
| 43 | +def print_contents(directory=None): |
| 44 | + print('\n'.join(gen_contents(directory))) |
54 | 45 |
|
55 | 46 |
|
56 |
| -print('\n'.join(gen_contents(notebooks))) |
| 47 | +if __name__ == '__main__': |
| 48 | + print_contents() |
| 49 | + print(70 * '#') |
| 50 | + print_contents('notebooks') |
0 commit comments