简体   繁体   English

IPython Notebook:计算笔记本中的单元格数

[英]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.回答问题 Stack Overflow,我使用相同的 ipython notebook,这使得搜索先前给出的答案更容易。

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. 我建议你不要使用相同的ipython笔记本。 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. 如果使用多个笔记本会导致重复代码,您应该能够将常用功能分解为您的笔记本可以导入的实际python模块。
  2. the notebook is just a json file, if you read the file as a json you can do it easily. 笔记本只是一个json文件,如果您将文件作为json读取,则可以轻松完成。

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. 实际上没有必要解析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). 或者,更简单, 只需在文本编辑器中打开.ipynb笔记本,然后突出显示相同的文本,并通过按ctrl + F(或任何绑定用于搜索)查看计数。

If any cells have markdown and you want to avoid those, you can just search on "cell_type": "code", too. 如果任何单元格有降价并且您想要避免这些,您可以只搜索"cell_type": "code",

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 . 其中: jupyter_notebook.ipynb应替换为您的filename.ipynb

With allow_errors=True , the notebook is executed until the end, regardless of any error encountered during the execution. 使用allow_errors=True时,无论执行过程中遇到任何错误,都会执行笔记本直到结束。 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 的单线

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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