Skip to content

Latest commit

 

History

History
62 lines (43 loc) · 2.17 KB

Jupyter_Notebooks_Count_code_characters.md

File metadata and controls

62 lines (43 loc) · 2.17 KB



Template request | Bug report | Generate Data Product

Tags: #jupyternotebooks #naas #jupyter-notebooks #read #codecharacters #snippet #operations #text

Author: Florent Ravenel

Description: This notebook provides a tool to count the number of characters in code written in Jupyter Notebooks.

Input

Import libraries

import json

Variables

# Input
notebook_path = "../template.ipynb"

Model

Get module libraries in notebook

def count_characters(notebook_path):
    with open(notebook_path) as f:
        nb = json.load(f)
    data = 0

    cells = nb.get("cells")
    # Check each cells
    for cell in cells:
        cell_type = cell.get("cell_type")
        sources = cell.get("source")
        for source in sources:
            if cell_type == "code":
                if not source.startswith("\n") and not source.startswith("#"):
                    char = source.replace(" ", "")
                    data += len(char)
    if data == 0:
        print("❎ No character of code wrote in notebook:", notebook_path)
    else:
        print(f"✅ {data} character(s) of code wrote in notebook:", notebook_path)
    return data

Output

Display result

no_characters = count_characters(notebook_path)
no_characters