0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ClaudeのエクスポートJSONをMarkdownに整形するPythonスクリプト

0
Posted at

背景

Claudeのチャット履歴はJSONでエクスポートできますが、そのままでは読みにくく活用しづらいです。チャットごとに分割してMarkdown化するPythonツールを作りました。

1. ファイル選択はtkinterのダイアログで十分

GUIを作り込まなくても、tkinter.filedialogを使えばファイル選択だけは簡単に実現できます。

import tkinter.filedialog as fd

p = fd.askopenfilename(filetypes=[("JSON files", "*.json")])
if not p:
    exit()

2. エンコーディングはUTF-8→cp932の順でフォールバック

日本語環境ではエクスポート元やツールによってエンコーディングが揺れることがあるため、まずUTF-8で読み、失敗したらShift-JIS(cp932)で再試行する構成にしています。

try:
    d = json.load(open(p, 'r', encoding='utf-8'))
except:
    d = json.load(open(p, 'r', encoding='cp932'))

3. タイムスタンプ付きフォルダで出力を管理

Path(__file__).parent(スクリプト自身の場所)を基準に、実行日時のフォルダを都度作成します。

from datetime import datetime
from pathlib import Path

output_dir = Path(__file__).parent / 'output' / datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir.mkdir(parents=True, exist_ok=True)

parents=Trueで親フォルダも自動作成、exist_ok=Trueで既存フォルダでもエラーにしません。

4. ファイル名の安全化

チャットタイトルをそのままファイル名にすると、Windowsで使えない文字(\ / : * ? " < > |)が含まれることがあるため、正規表現で置換します。

import re
filename = re.sub(r'[\\/:*?"<>|]', '_', title) + '.md'

5. 出力形式はシンプルなMarkdown

with open(output_dir / filename, 'w', encoding='utf-8') as f:
    f.write(f"# {title}\n\n")
    for m in c.get('chat_messages', []):
        f.write(f"**[{m['sender']}]**:\n\n{m['text']}\n\n")

sender(human/assistant)を太字見出しにして、メッセージ間を空行区切りにするだけの単純な構成ですが、後から読み返す・検索するには十分です。

まとめ

GUI操作(ファイル選択)とCLI的な処理を組み合わせるだけで、実用的なエクスポートツールになります。完全なソースコードと応用例(バッチ処理・カテゴリ分類・日付フィルタ)はこちらにまとめています。

Claudeチャットを資産化するPythonツール(ブログ)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?