jiks999/intimate-relationships-skill
intimate-relationships
Verified聊爱情/依恋/分手/冲突/关系话题时引用《亲密关系》(米勒)实证结论。
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 5.4 KB |
| references/notes-full.md | markdown | 37.1 KB |
| scripts/chatlog_to_markdown.py | script | 12.9 KB |
scripts/chatlog_to_markdown.py
View on GitHub#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
chatlog_to_markdown.py —— 把微信 / QQ / 通用聊天记录导出文件,转成适合分析的
结构化 Markdown 对话稿(并可选做匿名化与分块)。
设计目标:零依赖(仅标准库),在本地跑,数据不出机器。
支持输入:
*.txt 微信(留痕 / WeChatExporter 等)与 QQ 导出的常见三种版式,自动嗅探:
1) 时间行 + 发送者行 + 正文行(最常见)
2) 一行式: 2024-01-01 12:00:00 张三 正文
3) 日期分隔行:========== 2024-01-01 ==========
*.csv 表头含 时间/发送者/内容(列名容忍中英文与多种写法),逗号或制表符分隔
*.json [{"time": "...", "sender": "...", "content": "..."}, ...]
用法:
python3 chatlog_to_markdown.py chat.txt
python3 chatlog_to_markdown.py chat.txt --anonymize --stats
python3 chatlog_to_markdown.py chat.txt --chunk 800 --outdir ./out
输出:
<输入名>.transcript.md 完整对话稿
<输入名>.chunk-001.md ... 仅当指定 --chunk 时
"""
from __future__ import annotations
import argparse
import csv
import json
import re
import sys
from collections import Counter
from dataclasses import dataclass
from datetime import datetime
from pathlib import Path
from typing import Iterable, List, Optional
# --------------------------------------------------------------------------- #
# 数据结构
# --------------------------------------------------------------------------- #
TS_PATTERNS = [
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y-%m-%d %H:%M:%S ",
"%Y年%m月%d日 %H:%M:%S",
"%Y年%m月%d日 %H:%M",
]
TS_RE = re.compile(
r"^\s*(?P<ts>\d{4}[-/年]\d{1,2}[-/月]\d{1,2}日?(?:\s+\d{1,2}:\d{2}(?::\d{2})?)?)\s*$"
)
TS_INLINE_RE = re.compile(
r"^\s*(?P<ts>\d{4}[-/年]\d{1,2}[-/月]\d{1,2}日?\s+\d{1,2}:\d{2}(?::\d{2})?)\s*(?P<rest>.*)$"
)
DATE_BAR_RE = re.compile(r"^\s*[=\-—*]{3,}\s*(?P<date>\d{4}[-/年]\d{1,2}[-/月]\d{1,2}日?)\s*[=\-—*]{3,}\s*$")
SYSTEM_HINTS = (
"撤回了一条消息",
"邀请你加入了群聊",
"退出了群聊",
"以上是打招呼的内容",
"你已添加了",
"消息已发出,但被对方拒收了",
"[图片]",
"[表情]",
"[语音]",
"[视频]",
"[文件]",
"[动画表情]",
"[位置]",
"[链接]",
)
@dataclass
class Msg:
ts: Optional[datetime]
sender: str
content: str
raw_ts: str = ""
@property
def ts_label(self) -> str:
if self.ts:
return self.ts.strftime("%Y-%m-%d %H:%M")
return self.raw_ts or "时间未知"
# --------------------------------------------------------------------------- #
# 解析
# --------------------------------------------------------------------------- #
def _parse_ts(text: str) -> Optional[datetime]:
clean = text.strip().rstrip("日").replace("年", "-").replace("月", "-").replace("/", "-")
clean = re.sub(r"-(\d)\b", r"-0\1", clean) # 2024-1-3 -> 2024-01-03
for fmt in TS_PATTERNS:
try:
return datetime.strptime(text.strip(), fmt)
except ValueError:
continue
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
try:
return datetime.strptime(clean, fmt)
except ValueError:
continue
try:
return datetime.strptime(clean, "%Y-%m-%d")
except ValueError:
return None
def parse_txt(path: Path) -> List[Msg]:
"""嗅探三种常见 txt 版式。"""
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
msgs: List[Msg] = []
i = 0
cur_date_bar: Optional[str] = None
n = len(lines)
while i < n:
line = lines[i]
stripped = line.strip()
if not stripped:
i += 1
continue
m_bar = DATE_BAR_RE.match(stripped)
if m_bar:
cur_date_bar = m_bar.group("date")
i += 1
continue
# 版式 1:纯时间行
m_ts = TS_RE.match(stripped)
if m_ts:
ts_text = m_ts.group("ts")
raw_ts = ts_text
if cur_date_bar and not re.search(r"\d{1,2}:\d{2}", ts_text):
ts_text = f"{cur_date_bar} {ts_text}"
sender = lines[i + 1].strip() if i + 1 < n else ""
i += 2
body: List[str] = []
while i < n and lines[i].strip() and not TS_RE.match(lines[i].strip()) \
and not TS_INLINE_RE.match(lines[i].strip()) \
and not DATE_BAR_RE.match(lines[i].strip()):
body.append(lines[i].rstrip())
i += 1
msgs.append(Msg(_parse_ts(ts_text), sender, "\n".join(body).strip(), raw_ts))
continue
# 版式 2:一行式 时间 + 发送者 + 正文
m_inline = TS_INLINE_RE.match(line)
if m_inline:
rest = m_inline.group("rest").strip()
sender, _, content = rest.partition("\t")
if not _:
parts = re.split(r"\s{1,4}", rest, maxsplit=1)
sender = parts[0] if parts else rest
content = parts[1] if len(parts) > 1 else ""
msgs.append(Msg(_parse_ts(m_inline.group("ts")), sender, content.strip()))
i += 1
continue
# 无时间戳的续行:并到上一条
if msgs:
msgs[-1].content = (msgs[-1].content + "\n" + line.rstrip()).strip()
i += 1
return msgs
def parse_csv(path: Path) -> List[Msg]:
text = path.read_text(encoding="utf-8-sig", errors="replace")
dialect = csv.Sniffer().sniff(text[:4096], delimiters=",\t;")
rows = list(csv.DictReader(text.splitlines(), dialect=dialect))
if not rows:
return []
def pick(row: dict, keys: Iterable[str]) -> Optional[str]:
for k in row:
if k is None:
continue
norm = k.strip().lower()
for key in keys:
if key in norm:
return row[k]
return None
msgs = []
for row in rows:
ts_raw = pick(row, ("时间", "date", "time", "时刻")) or ""
sender = pick(row, ("发送者", "昵称", "sender", "from", "user", "name")) or "未知"
content = pick(row, ("内容", "正文", "message", "content", "text")) or ""
msgs.append(Msg(_parse_ts(ts_raw), sender, content, ts_raw))
return msgs
def parse_json(path: Path) -> List[Msg]:
data = json.loads(path.read_text(encoding="utf-8", errors="replace"))
if isinstance(data, dict):
for key in ("messages", "data", "records", "list"):
if isinstance(data.get(key), list):
data = data[key]
break
msgs = []
for item in data if isinstance(data, list) else []:
if not isinstance(item, dict):
continue
def first(*keys: str) -> str:
for k in keys:
for kk in item:
if kk.lower() == k:
return str(item[kk] or "")
return ""
ts_raw = first("time", "ts", "date", "timestamp", "时间")
msgs.append(
Msg(
_parse_ts(ts_raw),
first("sender", "from", "name", "昵称", "发送者") or "未知",
first("content", "text", "message", "内容"),
ts_raw,
)
)
return msgs
def load(path: Path) -> List[Msg]:
suffix = path.suffix.lower()
if suffix == ".csv":
return parse_csv(path)
if suffix == ".json":
return parse_json(path)
return parse_txt(path)
# --------------------------------------------------------------------------- #
# 输出
# --------------------------------------------------------------------------- #
def anonymize(msgs: List[Msg]) -> dict:
"""按发言量降序,把发送者替换为 甲/乙/丙…。返回映射表。"""
counts = Counter(m.sender for m in msgs if m.sender)
labels = "甲乙丙丁戊己庚辛壬癸子丑寅卯"
mapping = {name: labels[i % len(labels)] + ("" if i < len(labels) else str(i))
for i, (name, _) in enumerate(counts.most_common())}
for m in msgs:
m.sender = mapping.get(m.sender, m.sender)
return mapping
def render(msgs: List[Msg], title: str, stats: bool) -> str:
out = [f"# 对话稿:{title}", ""]
if stats:
out += ["## 概览", ""]
out += ["```", *stats_lines(msgs), "```", ""]
out += ["## 正文", ""]
day = None
for m in msgs:
if m.ts and m.ts.date() != day:
day = m.ts.date()
out += ["", f"### {day.isoformat()}", ""]
body = m.content.strip() or "(空)"
out.append(f"**{m.sender or '未知'}** · {m.ts_label} ")
out.append(f"> {body.replace(chr(10), chr(10) + '> ')}")
out.append("")
return "\n".join(out).rstrip() + "\n"
def stats_lines(msgs: List[Msg], gap_minutes: int = 60) -> List[str]:
if not msgs:
return ["无有效消息"]
counts = Counter(m.sender for m in msgs)
times = [m.ts for m in msgs if m.ts]
lines = [f"消息总数:{len(msgs)}", f"参与人数:{len(counts)}"]
for name, c in counts.most_common():
share = c / len(msgs) * 100
lines.append(f" · {name}: {c} 条 ({share:.1f}%)")
if times:
lines.append(f"时间跨度:{min(times):%Y-%m-%d %H:%M} → {max(times):%Y-%m-%d %H:%M}")
lines.append(f"有日期覆盖天数:{len({t.date() for t in times})} 天")
# 会话轮次(间隔 > gap_minutes 视为新一段对话)
sessions, last = 0, None
for t in sorted(times):
if last is None or (t - last).total_seconds() > gap_minutes * 60:
sessions += 1
last = t
lines.append(f"会话段数(间隔>{gap_minutes}分钟切分):{sessions}")
return lines
def chunk_and_write(text: str, base: Path, size: int) -> List[Path]:
"""按行切块,便于逐块喂给模型。"""
lines = text.splitlines()
chunks, cur, cur_len = [], [], 0
for ln in lines:
cur.append(ln)
cur_len += len(ln) + 1
if cur_len >= size:
chunks.append(cur)
cur, cur_len = [], 0
if cur:
chunks.append(cur)
paths = []
total = len(chunks)
for idx, block in enumerate(chunks, 1):
p = base.with_suffix(f".chunk-{idx:03d}.md")
header = f"<!-- 第 {idx}/{total} 块,共 {len(block)} 行 -->\n"
p.write_text(header + "\n".join(block) + "\n", encoding="utf-8")
paths.append(p)
return paths
# --------------------------------------------------------------------------- #
def main(argv: Optional[List[str]] = None) -> int:
ap = argparse.ArgumentParser(description="聊天记录 → 结构化 Markdown 对话稿")
ap.add_argument("input", help="输入文件:.txt / .csv / .json")
ap.add_argument("--out", help="输出文件名(默认 <输入名>.transcript.md)")
ap.add_argument("--outdir", help="输出目录(默认与输入同目录)")
ap.add_argument("--anonymize", action="store_true", help="匿名化发送者(甲/乙/丙…)")
ap.add_argument("--stats", action="store_true", help="在文首插入统计概览")
ap.add_argument("--chunk", type=int, metavar="N", help="按 N 字符切成多块,便于分批分析")
ap.add_argument("--gap", type=int, default=60, help="会话切分间隔,单位分钟(默认 60)")
args = ap.parse_args(argv)
src = Path(args.input).expanduser()
if not src.exists():
print(f"找不到文件:{src}", file=sys.stderr)
return 1
msgs = [m for m in load(src) if (m.content or "").strip() or m.sender]
if not msgs:
print("未能从该文件解析出任何消息,请检查版式(可先取前 50 行人工确认)。", file=sys.stderr)
return 2
mapping = anonymize(msgs) if args.anonymize else {}
title = f"{src.stem}(已匿名化)" if args.anonymize else src.stem
body = render(msgs, title, stats=args.stats)
outdir = Path(args.outdir).expanduser() if args.outdir else src.parent
outdir.mkdir(parents=True, exist_ok=True)
out = Path(args.out) if args.out else outdir / f"{src.stem}.transcript.md"
out.write_text(body, encoding="utf-8")
print(f"✓ 解析 {len(msgs)} 条消息 → {out}")
if mapping:
print(" 匿名映射:" + ",".join(f"{k} → {v}" for k, v in mapping.items()))
if args.stats:
print("\n".join(" " + ln for ln in stats_lines(msgs, args.gap)))
if args.chunk:
paths = chunk_and_write(body, out, args.chunk)
print(f"✓ 切分 {len(paths)} 块:{paths[0].name} … {paths[-1].name}")
print("\n提示:把对话稿或分块交给模型时,先说明你要分析的关系问题(争执模式/"
"表露深度/回应性/退出成本),再让它对着 references/notes-full.md 的对应章节作答。")
return 0
if __name__ == "__main__":
raise SystemExit(main())
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack." | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |
| ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |