Created
June 6, 2024 11:07
-
-
Save TarickWake/3c471bce6039da8b4f447f13b6796c7f to your computer and use it in GitHub Desktop.
This function opens a Jupyter notebook file and searches for a specific pattern in the outputs of the code cells. If the pattern is found, it returns the first group of the match as a float.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import codecs | |
import nbformat | |
import re | |
def grab_value_from_notebook(file_path, pattern): | |
""" | |
This function opens a Jupyter notebook file and searches for a specific pattern in the outputs of the code cells. | |
If the pattern is found, it returns the first group of the match as a float. | |
""" | |
# Open the notebook file | |
with codecs.open(file_path, 'r', encoding='utf-8') as file: | |
notebook = nbformat.read(file, as_version=4) | |
# Iterate over the cells in the notebook | |
for cell in notebook.cells: | |
# Check if the cell is a code cell | |
if cell.cell_type == "code": | |
# Check if the cell has outputs | |
if cell.outputs: | |
# Parse the outputs of the cell | |
for output in cell.outputs: | |
if output.output_type == "display_data": | |
for data_type, data_value in output.data.items(): | |
if data_type == "text/html": | |
# Search for the pattern in the output data | |
match = re.search(pattern, data_value) | |
if match: | |
# The first group contains the value of Re | |
grab_res = match.group(1) | |
# Return the value as a float | |
return float(grab_res) | |
def grab_str_from_notebook(file_path, pattern): | |
with codecs.open(file_path, 'r', encoding='utf-8') as file: | |
notebook = nbformat.read(file, as_version=4) | |
# Iterate over the cells | |
for cell in notebook.cells: | |
# Check if the cell is a code cell | |
if cell.cell_type == "code": | |
# Check if the cell has outputs | |
if cell.outputs: | |
# Parse the outputs | |
for output in cell.outputs: | |
if output.output_type == "display_data": | |
for data_type, data_value in output.data.items(): | |
if data_type == "text/html": | |
# Search for the pattern | |
match = re.search(pattern, data_value) | |
if match: | |
# The first group contains the value of Re | |
grab_res = match.group(1) | |
return str(grab_res) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment