如何为Jupyter Notebook新单元格设置默认'nocell'标签?
Absolutely! You don’t have to manually add the nocell tag to every new cell—you can configure Jupyter Notebook to do this automatically. Here are two straightforward approaches:
1. Use a Pre-Save Hook (Native, No Extra Installs)
This method adds the nocell tag to all cells (code and markdown) whenever you save your notebook, ensuring every new cell gets tagged after its first save.
First, generate your Jupyter config file if you haven’t already. Open your terminal and run:
jupyter notebook --generate-configThis will create a file at
~/.jupyter/jupyter_notebook_config.py(on Linux/macOS) orC:\Users\YourName\.jupyter\jupyter_notebook_config.py(Windows).Open this config file in a text editor, scroll to the bottom, and add the following code:
c = get_config() def add_default_tag(model, **kwargs): # Target both code and markdown cells if model['type'] in ['code', 'markdown']: # Make sure the metadata.tags field exists model['metadata'].setdefault('tags', []) # Add 'nocell' if it's not already present if 'nocell' not in model['metadata']['tags']: model['metadata']['tags'].append('nocell') # Register the hook to run before saving the notebook c.FileContentsManager.pre_save_hook = add_default_tagSave the config file and restart Jupyter Notebook. Now, any new cell you create will get the
nocelltag as soon as you save the notebook.
2. Use the Cell Tags Extension (Instant Tag Visibility)
If you want the tag to appear immediately when you create a cell (without waiting for a save), use the Cell Tags extension from jupyter_contrib_nbextensions:
First, install the extensions package and its dependencies:
pip install jupyter_contrib_nbextensions jupyter contrib nbextension install --userEnable the Cell Tags extension:
jupyter nbextension enable celltags/mainOpen Jupyter Notebook, go to the Edit menu, select Edit Notebook Metadata, and add the following to the JSON object:
"celltags": { "default_tags": ["nocell"] }Save the metadata, and from now on every new cell you create will have the
nocelltag right away.
Either method will save you the hassle of manual tagging. The pre-save hook is great if you prefer not to install extra tools, while the extension gives you instant visibility of the tag.
内容的提问来源于stack exchange,提问作者Manu

