In [1]:
def nb2subnb(filename, *, cell_type='markdown',
single_nb=False, keep_cells=[], keep_texts=[]):
r"""
(nb2subnb) splits out typed cells of jupyter
notebooks into n sub-notebooks.
examples:
# split into n markdown cell notebooks
nb2subnb(r'C:\temp\UsingJodliterate.ipynb')
# split into n code cell notebooks
nb2subnb(r'C:\temp\UsingJodliterate.ipynb',
cell_type='code')
# all markdown cells in single notebook
nb2subnb(r'C:\temp\UsingJodliterate.ipynb',
single_nb='True')
# code cells with numbers in range as single notebook
nb2subnb(r'C:\temp\UsingJodliterate.ipynb',
cell_type='code', single_nb='True',
keep_cells=list(range(10)))
# markdown cells with strings 'Bhagavad' or 'github'
nb2subnb(r'C:\temp\UsingJodliterate.ipynb',
single_nb='True',
keep_texts=['Bhagavad','github'])
# all code cells in range with string 'pacman'
nb2subnb(r'C:\temp\UsingJodliterate.ipynb',
cell_type='code',
keep_texts=['pacman'], keep_cells=list(range(30)))
"""
with open(filename) as in_file:
nb_data = json.load(in_file)
# notebook file name without extension/path
nbname = os.path.basename(os.path.splitext(filename)[0])
nb_cells, one_cell, nb_files = dict(), list(), list()
for cnt, cell in enumerate(nb_data['cells']):
if nb_data['cells'][cnt]['cell_type'] == cell_type:
if not single_nb:
# single cell notebooks
nb_cells, one_cell = dict(), list()
if 0 == len(keep_cells) or cnt in keep_cells:
if text_in_source(cell, keep_texts):
one_cell.append(cell)
nb_cells["cells"] = one_cell
nb_cells = insert_nb_metadata(
nb_data, nb_cells)
nb_out_file = NB_DIRECTORY + \
nbname + '-' + cell_type + \
'-' + str(cnt) + '.ipynb'
nb_files.append(nb_out_file)
with open(nb_out_file, 'w') as out_file:
json.dump(nb_cells, out_file,
ensure_ascii=False)
elif single_nb:
# single notebook with only (cell_type) cells
if 0 == len(keep_cells) or cnt in keep_cells:
if text_in_source(cell, keep_texts):
one_cell.append(cell)
nb_cells["cells"] = one_cell
if single_nb:
nb_out_file = NB_DIRECTORY + \
nbname + '-' + cell_type + '-only.ipynb'
nb_files.append(nb_out_file)
nb_cells = insert_nb_metadata(nb_data, nb_cells)
with open(nb_out_file, 'w') as out_file:
json.dump(nb_cells, out_file,
ensure_ascii=False)
# list of generated sub-notebooks
return nb_files
In [2]:
# append nb2* script directory to system path
import sys
sys.path.append(r'C:\temp\nb2wp')
In [3]:
# notebook file
nb_file = r'C:\temp\nb2wp\UsingJodliterate.ipynb'
In [4]:
nb2subnb_opts = {
'single_nb': False,
'cell_type': 'code',
'keep_cells': [2, 8, 21],
'keep_texts': []
}
In [5]:
import nb2wput as nbu
# split notebook into selected parts and convert to HTML
nbu.nb2wpblk(nb_file, nb2subnb_parms=nb2subnb_opts)
One thought on “Better Blogging with Jupyter Notebooks on WordPress.com”