Files
cuotibiye/analysis/channels.py
T

187 lines
7.1 KiB
Python
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""把抖音 / 闲鱼采集到的 jsonl 汇成一份短报告。
这两个渠道的数据不并进 xhs.db 的 comments 表——它们的语气和口径跟小红书评论不一样,
混在一起算「信号占比」会失真。单独出一份 channels.md,用来看两件事:
1. 闲鱼:哪些商品在「买完就转手」(弃用信号命中率、价格带、原话)
2. 抖音:评论里在抱怨什么(高频词 + 高赞评论)
用法:
python analysis/channels.py
python analysis/channels.py --raw data/raw --out data/out/channels.md
"""
from __future__ import annotations
import argparse
import json
import re
import statistics
from collections import Counter
from pathlib import Path
ABANDON_HINT = ["吃灰", "闲置", "未拆", "用了两次", "用了几次", "不常用", "不用了",
"低价出", "转卖", "回血", "半价", "出闲置", "智商税", "后悔", "腾地方"]
# 评论里常见的抱怨方向,只用来给抖音评论分堆
COMPLAIN = {
"贵/会员": ["贵", "会员", "vip", "VIP", "收费", "订阅", "续费", "套路"],
"不好用/麻烦": ["麻烦", "费劲", "折腾", "不好用", "鸡肋", "吃灰", "闲置"],
"孩子不配合": ["不配合", "不愿", "抵触", "坐不住", "偷懒", "糊弄"],
"效果怀疑": ["有用吗", "没用", "智商税", "焦虑", "割韭菜", "智商"],
"替代方案": ["直接打印", "免费", "小程序", "表格", "excel", "Excel", "微信"],
}
STOP = set("的 了 是 我 你 他 她 它 也 就 都 还 和 与 在 有 没 不 很 太 这 那 个 一 啊 吧 呢 吗 呀 哦 嗯".split())
def load(raw: Path):
xy, dv, dc = [], [], []
for f in sorted(raw.glob("*.jsonl")):
with f.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except json.JSONDecodeError:
continue
t = r.get("type")
if t == "xy_item":
xy.append(r)
elif t == "dy_video":
dv.append(r)
elif t == "dy_comment":
dc.append(r)
return xy, dv, dc
def dedupe(rows, key):
seen, out = set(), []
for r in rows:
k = r.get(key)
if not k or k in seen:
continue
seen.add(k)
out.append(r)
return out
def bigrams(texts, n=2):
c = Counter()
for t in texts:
# 按标点/英文数字切段再取 n-gram,避免「同款,用了」拼成「款用」这种假词
for seg in re.findall(r"[\u4e00-\u9fa5]+", t):
if len(seg) < n:
continue
for i in range(len(seg) - n + 1):
g = seg[i:i + n]
if any(ch in STOP for ch in g):
continue
c[g] += 1
return c
def md_xy(xy, limit=8):
out = ["## 一、闲鱼:谁在把东西转手", ""]
if not xy:
out += ["_没有 xy_*.jsonl 数据。先跑 `node collector/xianyu.mjs run --keywords 错题打印机`。_", ""]
return out
by_kw = {}
for r in xy:
by_kw.setdefault(r.get("keyword") or "未标注", []).append(r)
out += ["| 关键词 | 商品数 | 带弃用信号 | 占比 | 价格中位数 |", "|---|---|---|---|---|"]
for kw, rows in sorted(by_kw.items(), key=lambda kv: -len(kv[1])):
hit = [r for r in rows if int(r.get("abandon_count") or 0) > 0]
prices = [float(r.get("price") or 0) for r in rows if float(r.get("price") or 0) > 0]
med = statistics.median(prices) if prices else 0
out.append(f"| {kw} | {len(rows)} | {len(hit)} | {len(hit) / len(rows) * 100:.0f}% | ¥{med:.0f} |")
out.append("")
words = Counter()
for r in xy:
for w in str(r.get("abandon_hits") or "").split("|"):
if w:
words[w] += 1
if words:
out += ["高频弃用词:" + "、".join(f"{w}({n})" for w, n in words.most_common(10)), ""]
out += ["最像「买了没用」的几条:", ""]
ranked = sorted(xy, key=lambda r: -int(r.get("abandon_count") or 0))[:limit]
for r in ranked:
if int(r.get("abandon_count") or 0) <= 0:
continue
out.append(f"- ¥{r.get('price') or '?'} · {r.get('title', '')[:50]} `{r.get('abandon_hits', '')}`")
out.append("")
return out
def md_dy(dv, dc, limit=10):
out = ["## 二、抖音:评论区在说什么", ""]
if not dv and not dc:
out += ["_没有 dy_*.jsonl 数据。先跑 `node collector/douyin.mjs run --keywords 错题本`。_", ""]
return out
if dv:
out += [f"视频 {len(dv)} 条。播放量靠前的:", ""]
for v in sorted(dv, key=lambda r: -int(r.get("digg_count") or 0))[:5]:
out.append(f"- 赞{v.get('digg_count') or 0} 评{v.get('comment_count') or 0} · {str(v.get('desc') or '')[:56]}")
out.append("")
if not dc:
out += ["_没有抓到评论。视频页评论是懒加载的,调大 `--comment-rounds` 或换几条视频。_", ""]
return out
texts = [str(r.get("content") or "") for r in dc]
hits = Counter()
for t in texts:
for name, words in COMPLAIN.items():
if any(w in t for w in words):
hits[name] += 1
out += [f"评论 {len(dc)} 条,按抱怨方向分堆(可重复命中):", "", "| 方向 | 条数 | 占比 |", "|---|---|---|"]
for name, n in hits.most_common():
out.append(f"| {name} | {n} | {n / len(dc) * 100:.0f}% |")
out.append("")
top = bigrams(texts, 2).most_common(12)
if top:
out += ["高频词:" + "、".join(f"{w}({n})" for w, n in top), ""]
out += ["高赞评论:", ""]
for r in sorted(dc, key=lambda r: -int(r.get("like_count") or 0))[:limit]:
c = str(r.get("content") or "").replace("\n", " ")[:90]
out.append(f"- {r.get('like_count') or 0} 赞:{c}")
out.append("")
return out
def main():
ap = argparse.ArgumentParser(description="抖音 / 闲鱼数据汇总")
ap.add_argument("--raw", default="data/raw")
ap.add_argument("--out", default="data/out/channels.md")
args = ap.parse_args()
raw = Path(args.raw)
if not raw.exists():
print(f"找不到 {raw}")
raise SystemExit(1)
xy, dv, dc = load(raw)
if not (xy or dv or dc):
print(f"{raw} 里没有 xy_*.jsonl / dy_*.jsonl。先跑对应的采集器。")
raise SystemExit(1)
xy = dedupe(xy, "item_id")
dv = dedupe(dv, "video_id")
dc = dedupe(dc, "comment_id")
lines = ["# 抖音 / 闲鱼渠道汇总", ""]
lines += [f"数据:闲鱼商品 {len(xy)} 条、抖音视频 {len(dv)} 条、抖音评论 {len(dc)} 条。", ""]
lines += md_xy(xy)
lines += md_dy(dv, dc)
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text("\n".join(lines), encoding="utf-8")
print(f"已写入 {out}")
print(f" 闲鱼商品 {len(xy)} 条 / 抖音视频 {len(dv)} 条 / 抖音评论 {len(dc)} 条")
if __name__ == "__main__":
main()