Last active
October 15, 2018 10:34
-
-
Save jnishii/555c87a2219d35fb3f082e1e3a13c51e to your computer and use it in GitHub Desktop.
Clear the source and output cells in code blocks of jupyter/ipython sheets
This file contains 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
""" | |
Clear jupyter/ipython sheets by | |
- removing the source cell and output cells in code blocks | |
- removing highlight tag in markdown block by the highlighter extension | |
Usage: | |
python nb_clear_code_block.py notebook.ipynb <notebook2.ipynb ...> | |
Modified | |
from https://github.com/flexxui/flexx-notebooks/blob/master/remove_output.py | |
by Jun Nishii | |
Gist: https://gist.github.com/jnishii/555c87a2219d35fb3f082e1e3a13c51e | |
""" | |
import sys | |
import io | |
import os | |
import nbformat | |
import re | |
def clear_code_block(nb): | |
for cell in nb.cells: | |
if cell.cell_type == 'code': | |
cell.source = [] | |
cell.outputs = [] | |
def clear_highlight(nb): | |
for cell in nb.cells: | |
if cell.cell_type == 'markdown': | |
cell.source = re.sub('<span class=\\"mark\\">(.*)</span>','\\1',cell.source) | |
if __name__ == '__main__': | |
for fname in sys.argv[1:]: | |
print(fname) | |
with io.open(fname, 'r', encoding='utf-8') as f: | |
nb = nbformat.read(f, as_version=4) | |
clear_code_block(nb) | |
clear_highlight(nb) | |
base, ext = os.path.splitext(fname) | |
new_ipynb = "%s_workbook%s" % (base, ext) | |
with io.open(new_ipynb, 'w', encoding='utf8') as f: | |
nbformat.write(nb, f, version=4) | |
print("wrote %s" % new_ipynb) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment