Issue
I have an iPython notebook that I used to use with Jupyter Notebook. Suddenly I found that when I open this particular notebook with Jupyter (Notebook or Lab), the window becomes unresponsive and it crashes after 30 sec or so. Sometimes it shows MathJax is loading.
I have tried opening this in completely separate Conda environments (even in different computers) but face the same issue. This leads me to believe that I did something wrong (possibly with MathJax) with this notebook last time.
I want to copy the important codes from this notebook. What are my options? Can I read it in some sort of text mode just to copy the codes to a fresh notebook?
Solution
The following script prints the code blocks properly (using nbformat
):
import nbformat
def extract_code_from_notebook(notebook_path):
with open(notebook_path, 'r', encoding='utf-8') as f:
notebook = nbformat.read(f, as_version=4)
code_cells = [cell['source'] for cell in notebook['cells'] if cell['cell_type'] == 'code']
return code_cells
notebook_path = 'notebook_name.ipynb'
try:
extracted_code = extract_code_from_notebook(notebook_path)
for i, code_cell in enumerate(extracted_code, start=1):
print(f"Code Cell {i}:\n{code_cell}\n{'='*30}\n")
except Exception as e:
print(f"An error occurred: {e}")
Answered By - deltasata
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.