-
Notifications
You must be signed in to change notification settings - Fork 1
/
toc_gen.py
executable file
·57 lines (45 loc) · 1.28 KB
/
toc_gen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
# level 1 is plain text with no prefix
# level 2 starts with ###, level 3 with an extra #
def get_level(line):
line = line.strip()
if len(line) == 0:
return 0
if line[0] == '#':
space_pos = line.find(' ')
return space_pos - 1
# 3 means level 2
# 4 means level 3
# ...
return 1
def print_toc_chapter(line,lvl_stack):
line = line.replace('# ','')
line = line.replace('#','')
link = line.lower()
link = link.replace('/','')
link = link.replace('?','')
link = link.replace(' ','-')
#print( ".".join([str(lvl) for lvl in lvl_stack]) + ' ' + line)
level = len(lvl_stack) - 1
spaces_before = 2 * level
print(spaces_before*' '+'* ['+line+'](#'+link+')')
f = open('final_toc.txt')
all_lines = f.readlines()
f.close()
last_level = 1
level_stack = [ 0 ]
for line in all_lines:
line = line.strip()
level = get_level(line)
if last_level < level:
level_stack.append(1)
elif last_level == level:
level_stack[-1] += 1
else: # last_level > level
diff = last_level - level
while diff > 0:
diff -= 1
level_stack.pop()
level_stack[-1] += 1
last_level = level
print_toc_chapter(line, level_stack)