-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathextract_code.py
31 lines (25 loc) · 995 Bytes
/
extract_code.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
"""Extracts code snippets from rst files of each chapter"""
import sys
import os
from docutils.core import publish_doctree
with open(sys.argv[1]) as f:
doctree = publish_doctree(f.read())
count = 0
titles = doctree.traverse(condition=lambda node: node.tagname == 'title')
for idx, title in enumerate(titles):
if title.astext() != 'How to do it':
continue
count += 1
section = title.parent
code_blocks = section.traverse(condition=lambda node: node.tagname == 'literal_block')
source_code = '\n'.join([block.astext() for block in code_blocks])
chapter_name = os.path.basename(sys.argv[1]).split('.')[0]
source_file = '%s/%s_%02d.py' % (chapter_name, chapter_name, count)
if os.path.exists(source_file):
continue
try:
os.makedirs(chapter_name)
except:
pass
with open(source_file, 'w') as s:
s.write(source_code)