Skip to content

Instantly share code, notes, and snippets.

@leoauri
Last active April 19, 2020 10:37
Show Gist options
  • Save leoauri/c971352fd5f104c555e7684792cc0b91 to your computer and use it in GitHub Desktop.
Save leoauri/c971352fd5f104c555e7684792cc0b91 to your computer and use it in GitHub Desktop.
Script to blank code from jupyter notebooks, leaving comments, outputs & markup intact, for practice
#!/usr/bin/env python3
# coding: utf-8
import json
import fire
from pathlib import Path
def blankt_cells(cells):
output_cells = []
for cell in cells:
if cell['cell_type'] == 'code':
cell['source'] = [code_line if code_line.strip().startswith('#')
else '\n' if code_line.endswith('\n')
else ''
for code_line in cell['source']]
output_cells.append(cell)
return output_cells
def save_path(input_path, version):
name_unblnkt = input_path.stem.split('-blnkt')[0]
return input_path.with_name(f'{name_unblnkt}-blnkt-{version:02}{input_path.suffix}')
def blankt_file(input_path, verbose):
input_file = json.load(open(input_path,'r',encoding="utf-8"))
input_file['cells'] = blankt_cells(input_file['cells'])
if verbose:
print(input_file)
version = 1
output_path = save_path(input_path, version)
# increment version until file doesn't exist
while output_path.exists():
version += 1
output_path = save_path(input_path, version)
with open(output_path, 'w') as output_file:
json.dump(input_file, output_file)
print(f'blankt notebook saved as {output_path}')
def main(input_path=None, verbose=False):
if not input_path:
print('No path provided')
else:
input_path = Path(input_path)
blankt_file(input_path, verbose)
if __name__ == '__main__': fire.Fire(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment