From inputfile, parse the JSON and remove those cells which have values of the basekey, which are in the list of tags to remove but not in the list of tags to remove.
"""
notebook=json.load(inputfile)
ifisinstance(keep,str):keep=[keep]
ifisinstance(remove,str):remove=[remove]
notebook_new=copy.deepcopy(notebook)
notebook_new["cells"]=[]
forcellinnotebook["cells"]:
keepcell=True
forkeyinremove:
cell_tags=None
ifbasekeyincell["metadata"]:
cell_tags=cell["metadata"][basekey]
ifisinstance(cell_tags,str):cell_tags=[cell_tags]
ifcell_tags==None:
ifkey=="all":
keepcell=False
ifcell_tags!=None:
ifkeyincell_tagsorkey=="all":
fortagincell_tags:
iftagnotinkeep:
keepcell=False
ifkeepcell==True:
notebook_new["cells"].append(cell)
returnnotebook_new
if__name__=='__main__':
parser=argparse.ArgumentParser(description='Split up Jupyter Notebook by cell metadata.\nSpecify tags to keep with `--keep`, specify tags to remove with `--remove`; multiple instances are ok. Special `--remove` tag: all (which removes all cells except those specified with `--keep`).\nAll tags will be read from BASEKEY, which usually is `exercise`, if you do not specify it differently.')
parser.add_argument('infile',type=argparse.FileType('r'),help="Input file to parse")
parser.add_argument('--output',"-o",type=str,help="Output file to parse")
parser.add_argument('--keep',"-k",action="append",help="Keep these tags.")
parser.add_argument('--remove',"-r",action="append",help="Remove these tags. Special: all (remove all except for keep).")
parser.add_argument('--basekey',type=str,help="Basekey to use for discriminating the tags.",default="exercise")