You can use the TagRemovePreprocessor to selectively remove entire cells, cell inputs, or cell outputs during conversion based on metadata tags assigned to the cells. The original notebook remains unchanged; only the exported output is modified.
To use this, assign specific tags to your cells in the notebook metadata. You can then configure the preprocessor to look for these specific tag strings.
Key configuration keys for TagRemovePreprocessor:
remove_cell_tags: A tuple of strings. Cells containing any of these tags will be removed entirely.remove_input_tags: A tuple of strings. The input code of cells containing these tags will be removed.remove_all_outputs_tags: A tuple of strings. The outputs of cells containing these tags will be removed.enabled: Boolean to enable/disable the preprocessor.
from traitlets.config import Config
import nbformat as nbf
from nbconvert.exporters import HTMLExporter
from nbconvert.preprocessors import TagRemovePreprocessor
# Setup config
c = Config()
# Configure tag removal
c.TagRemovePreprocessor.remove_cell_tags = ("remove_cell",)
c.TagRemovePreprocessor.remove_all_outputs_tags = ("remove_output",)
c.TagRemovePreprocessor.remove_input_tags = ("remove_input",)
c.TagRemovePreprocessor.enabled = True
# Configure and run exporter
c.HTMLExporter.preprocessors = ["nbconvert.preprocessors.TagRemovePreprocessor"]
exporter = HTMLExporter(config=c)
exporter.register_preprocessor(TagRemovePreprocessor(config=c), True)
# Run exporter - returns a tuple (html_content, notebook_metadata)
output = HTMLExporter(config=c).from_filename("your-notebook-file-path.ipynb")
# Write to output html file
with open("your-output-file-name.html", "w") as f:
f.write(output[0])