Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
allendowney
GitHub Repository: allendowney/thinkbayes2
Path: blob/master/soln/scrub_code.py
1901 views
1
#!/usr/bin/env python
2
"""
3
simple example script for scrubping solution code cells from IPython notebooks
4
5
Usage: `scrub_code.py foo.ipynb [bar.ipynb [...]]`
6
7
Marked code cells are scrubbed from the notebook
8
"""
9
10
import io
11
import os
12
import sys
13
14
import nbformat
15
16
def scrub_code_cells(nb):
17
scrubbed = 0
18
cells = 0
19
for cell in nb.cells:
20
if cell.cell_type != 'code':
21
continue
22
cells += 1
23
# scrub cells marked with initial '# Solution' comment
24
# any other marker will do, or it could be unconditional
25
if cell.source.startswith("# Solution"):
26
cell.source = u'# Solution goes here'
27
scrubbed += 1
28
29
# clear all outputs
30
cell.outputs = []
31
32
print("scrubbed %i/%i code cells" % (scrubbed, cells))
33
34
if __name__ == '__main__':
35
for filename in sys.argv[1:]:
36
print("reading %s" % filename)
37
# read
38
with io.open(filename, encoding='utf8') as f:
39
nb = nbformat.read(f, nbformat.NO_CONVERT)
40
41
# scrub
42
scrub_code_cells(nb)
43
44
# new name
45
base, ext = os.path.splitext(filename)
46
47
if base.endswith("soln"):
48
base = base.replace("soln", "")
49
base = base.rstrip("_")
50
base = '../' + base
51
else:
52
base = base + "_scrubbed"
53
54
new_filename = "%s%s" % (base, ext)
55
56
# write
57
print("writing %s" % new_filename)
58
with io.open(new_filename, 'w', encoding='utf8') as f:
59
nbformat.write(nb, f)
60
61