Count code characters
Tags: #naas #jupyter-notebooks #read #codecharacters #snippet
Author: Florent Ravenel

Input

Import libraries

1
import json
Copied!

Variables

1
# Input
2
notebook_path = "../template.ipynb"
Copied!

Model

Get module libraries in notebook

1
def count_characters(notebook_path):
2
with open(notebook_path) as f:
3
nb = json.load(f)
4
data = 0
5
6
cells = nb.get("cells")
7
# Check each cells
8
for cell in cells:
9
cell_type = cell.get('cell_type')
10
sources = cell.get('source')
11
for source in sources:
12
if cell_type == "code":
13
if not source.startswith('\n') and not source.startswith('#'):
14
char = source.replace(" ", "")
15
data += len(char)
16
if data == 0:
17
print("❎ No character of code wrote in notebook:", notebook_path)
18
else:
19
print(f"✅ {data} character(s) of code wrote in notebook:", notebook_path)
20
return data
Copied!

Output

Display result

1
no_characters = count_characters(notebook_path)
2
no_characters
Copied!
Copy link
Edit on GitHub