LoginSignup
0
1

More than 1 year has passed since last update.

【備忘録】開けなくなった ipython (jupyter) notebook からコード(cell)を抽出するコード

Posted at

jupyter notebook を雑に使っていると,適当に for 文中で書いた print 文のせいで開けなくなってしまうノートブックが生まれることがあります.
そんなときの方法として,いくつかオプションがありますが中身は json なのでコードを書けば解決可能です.

というわけで,以下のコードで解決可能です.

import json

# Load the IPython notebook as a JSON file
with open("filename.ipynb", "r") as f:
    ipynb = json.load(f)

# Extract the code cells from the JSON file
code_cells = [cell["source"] for cell in ipynb["cells"] if cell["cell_type"] == "code"]

# Save the code to a file
with open("code.py", "w") as f:
    for cell in code_cells:
        for line in cell:
            f.write(line)
        f.write("\n")

ありがとう chatGPT

上記のコード,chatGPT君が書いてくれました.そのため,コードの出どころ(著作者,著作権?)はわかりません.
私からお願いしたことは以下の通りです.

Please tell me how to get the code from ipython notebook by my own.
I cannot open ipynb file because it is too much to do.
Can you write an code to extract?

私は普段,vim で stdout を削っていました.
ちなみに,jupyter nbconvert も使いましたが依存関係のチェックのせいか全然終わらなかったです.
退屈なことは AI にお願いしましょう(自分でも書けますが,楽をしたいときにいいですね).

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1