1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Google ColabをMarkDown形式のテキストに整形するPythonコード

1
Posted at

整形イメージ

Google Colabの各セルを
image.png

このようなMarkDown形式に整形
image.png

動機

  • Google Colabから全セル内のテキストを取得するのは手間
  • セルの区切りがわかる形で複数まとめて取得したい

使い方

  • Colab の上部メニューから 「ファイル」 → 「ダウンロード」 → 「.ipynb をダウンロード」 を選択
  • "ColabToMd.py"ファイルを作成してエディタでソースコードを張り付ける
  • "ColabToMd.py"をクリックして、指示に従って保存したipynbファイルを指定する
  • "output.md"にテキスト化した結果が入っているので、生成AIへの質問等で活用する

ソースコード(Pythonファイル)

import json
from markdown import markdown
from bs4 import BeautifulSoup
import os

def markdown_to_text(md):
    # Markdown→HTML
    html = markdown(md)
    # HTML→テキスト
    soup = BeautifulSoup(html, 'html.parser')
    return soup.get_text()

def main():
    # 現在の作業ディレクトリを取得
    current_dir = os.getcwd()

    # IPYNBファイルの入力を促す
    ipynb_path = input("IPYNBファイルを入力してください: ")

    # output.mdの初期化
    output_file = os.path.join(current_dir, "output.md")

    # IPYNBファイルの存在チェック
    if not os.path.isfile(ipynb_path):
        with open(output_file, "w", encoding="utf-8") as file_output:
            file_output.write("指定されたIPYNBファイルは存在しません。\n")
        print("指定されたIPYNBファイルは存在しません。")
        return
    
    with open(ipynb_path, 'r', encoding='utf-8') as f:
        notebook = json.load(f)

    cnt = 1
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(f"# {ipynb_path}\n\n")
        for cell in notebook['cells']:
            text = ''.join(cell.get('source', []))
            cell_type = cell.get('cell_type', '')

            f.write("-----------------------------------------------------\n")
            f.write(f"## セル{cnt}{cell_type}セル)\n")
            f.write("-----------------------------------------------------\n")

            if cell_type == 'code':
                f.write("```python\n")
                f.write(text)
                f.write("\n```\n")
                # コードセルの出力を追加
                outputs = cell.get('outputs', [])
                for output in outputs:
                    output_type = output.get('output_type', '')
                    # 標準出力(printなど)
                    if output_type == 'stream':
                        f.write("**出力:**\n")
                        f.write("```\n")
                        f.write(''.join(output.get('text', [])))
                        f.write("\n```\n")
                    # 実行結果(式の値など)
                    elif output_type == 'execute_result':
                        f.write("**実行結果:**\n")
                        # 'text/plain'があればそれを表示
                        data = output.get('data', {})
                        if 'text/plain' in data:
                            f.write("```\n")
                            f.write(''.join(data['text/plain']))
                            f.write("\n```\n")
                    # エラー出力
                    elif output_type == 'error':
                        f.write("**エラー:**\n")
                        f.write("```\n")
                        f.write(''.join(output.get('traceback', [])))
                        f.write("\n```\n")
            else:  # markdownなど マークダウン→見かけ上のテキスト
                plain_text = markdown_to_text(text)
                f.write(plain_text)
                f.write('\n')
            f.write('\n')
            cnt += 1

    # 入力待ち
    input("続行するには何かキーを押してください...")

if __name__ == "__main__":
    main()

1
1
1

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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?