Template request | Bug report | Generate Data Product
Tags: #jupyternotebooks #naas #jupyter-notebooks #read #libraries #snippet #operations #text
Author: Florent Ravenel
Description: This notebook provides instructions on how to install and use libraries in Jupyter Notebooks.
import json
from pprint import pprint
# Input
notebook_path = "../template.ipynb"
def get_libraries(notebook_path):
with open(notebook_path) as f:
nb = json.load(f)
data = []
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 "from" in source and "import" in source:
lib = (
source.replace("\n", "")
.split("from")[-1]
.split("import")[0]
.strip()
)
module = (
source.replace("\n", "")
.split("import")[-1]
.split(" as ")[0]
.strip()
)
data.append(f"{lib}.{module}")
if "from" not in source and "import" in source:
library = (
source.replace("\n", "")
.split("import")[-1]
.split(" as ")[0]
.strip()
)
data.append(library)
if len(data) == 0:
print("❎ No library found in notebook:", notebook_path)
else:
print(f"✅ {len(data)} librarie(s) found in notebook:", notebook_path)
return data
libraries = get_libraries(notebook_path)
print(libraries)