简体   繁体   中英

IPython Notebook: Count number of cells in notebook

Answering questions Stack Overflow, I use the same ipython notebook, which makes its easier to search previously given answers.

The notebook is starting to slow down. The question I have is: How do I count the numbers of cells in the notebook?

  1. I recommend you don't use the same ipython notebook for everything. If using multiple notebooks would lead to repeat code, you should be able to factor out common functionality into actual python modules which your notebooks can import.
  2. the notebook is just a json file, if you read the file as a json you can do it easily.

For example:

import json    
document = json.load(open(filepath,'r'))
for worksheet in document['worksheets']:
    print len(worksheet['cells'])    

There's actually no need to parse the json. Just read it as text and count instances of, for example, "cell type":

with open(fname, 'r') as f:
    counter = 0
    for line in f:
        if '"cell_type":' in line:
            counter += 1

Or, even easier, just open your .ipynb notebook in a text editor, then highlight the same bit of text and see the count by hitting ctrl+F (or whatever the binding is for search).

If any cells have markdown and you want to avoid those, you can just search on "cell_type": "code", too.

Although as others have said, you're better off not storing your code this way. Or at least, I imagine you can store it in ways that will make it much easier to access in the future, if you want it for reference.

You could execute your notebook from the command line by:

jupyter nbconvert --ExecutePreprocessor.allow_errors=True --to notebook --execute jupyter_notebook.ipynb

where: jupyter_notebook.ipynb should be replaced with your filename.ipynb .

With allow_errors=True , the notebook is executed until the end, regardless of any error encountered during the execution. The output notebook, will contain the stack-traces and error messages for all the cells raising exceptions.

python -c "import sys, json; print(len(json.load(open(sys.argv[1],'r'))['cells']))" <notebook_filename.ipynb>

基于https://stackoverflow.com/a/38925464/588437 的单线

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM