Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count lines of code in jupyter notebook

I'm currently using Jupyter ipython notebook and the file I am working with has a lot of code. I am just curious as to how many lines of code there exactly are in my file. It is hard to count since I have separated my code into many different blocks.

For anyone who is experienced with jupyter notebook, how do you count how many total lines of code there are in the file?

Thanks!

Edit: I've figured out how to do this, although in a pretty obscure way. Here's how: download the jupyter notebook as a .py file, and then open the .py file in software like Xcode, or whatever IDE you use, and count the lines of code there.

like image 317
Cynthia Avatar asked Jul 28 '17 20:07

Cynthia


People also ask

How do you count lines of code in Python?

Use readlines() to get Line Count This is the most straightforward way to count the number of lines in a text file in Python. The readlines() method reads all lines from a file and stores it in a list.

How do you show line numbers in Jupyter Notebook VS code?

In VS Code Jupyter Notebook, you can toggle line numbers by pressing L.

How do you write multiple lines of code in Jupyter Notebook?

Multiline editing is one of the features which is not available in IPython terminal. In order to enter more than one statements in a single input cell, press ctrl+enter after the first line. Subsequently, just pressing enter will go on adding new line in the same cell.

How do I turn off line numbers in Jupyter Notebook?

Esc and 'l' will remove the numbering from current cell. Esc and 'L' will remove the numbering from all the cells of notebook.


1 Answers

This will give you the total number of LOC in one or more notebooks that you pass to the script via the command-line:

#!/usr/bin/env python

from json import load
from sys import argv

def loc(nb):
    cells = load(open(nb))['cells']
    return sum(len(c['source']) for c in cells if c['cell_type'] == 'code')

def run(ipynb_files):
    return sum(loc(nb) for nb in ipynb_files)

if __name__ == '__main__':
    print(run(argv[1:]))

So you could do something like $ ./loc.py nb1.ipynb nb2.ipynb to get results.

like image 135
Jessime Kirk Avatar answered Sep 24 '22 17:09

Jessime Kirk