chore: 首次纳入版本控制(审查前基线,v1.2.0)
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
"""把 comments.csv / notes.csv 变成一份可直接读的需求报告。
|
||||
|
||||
用法:
|
||||
python analysis/analyze.py
|
||||
python analysis/analyze.py --db data/out/xhs.db --out data/out/report.md
|
||||
|
||||
做的事:
|
||||
1. 基本盘:笔记数、评论数、互动分布
|
||||
2. 需求信号分类:把评论按"关心什么"归到 8 类,给出条数和原话
|
||||
3. 高频词:中文 2~4 字组合统计(够用,不需要分词库)
|
||||
4. 竞品提及:统计评论里出现的其他产品名
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import re
|
||||
import sqlite3
|
||||
import sys
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
# 需求信号分类:直接对应做产品时要回答的问题
|
||||
SIGNALS = {
|
||||
"想试用/要免费": r"试用|免费|白嫖|体验一下|能先|先试试|不要钱",
|
||||
"价格/计费": r"多少钱|价格|太贵|贵了|便宜|收费|怎么收|积分|token|年费|续费|包月",
|
||||
"怎么买/在哪用": r"怎么买|哪里买|在哪买|链接|下单|购买|咋买|怎么用|在哪用|入口|二维码",
|
||||
"设备/形态": r"手机|电脑|平板|ipad|iPad|app|App|APP|小程序|网页|学习机|客户端|安装|下载",
|
||||
"科目/年级": r"数学|语文|英语|物理|化学|生物|历史|地理|小学|初中|高中|年级|几年级",
|
||||
"打印/导出": r"打印|导出|pdf|PDF|打印机|纸质|手抄|抄写",
|
||||
"质疑/劝退": r"智商税|没用|鸡肋|差生文具多|自己整理|没必要|收割|割韭菜|广告|套路|不靠谱",
|
||||
"求同类推荐": r"有没有.*推荐|求推荐|哪个好|对比|替代|平替|别的|其他.*(软件|工具|app)",
|
||||
}
|
||||
|
||||
BRANDS = [
|
||||
"豆包", "作业帮", "小猿", "猿辅导", "夸克", "学而思", "步步高", "科大讯飞",
|
||||
"喵喵机", "汉印", "错题打印机", "错题本", "全能扫描王", "扫描全能王",
|
||||
"复盘错题本", "错题记忆卡", "学习机", "AI错题", "文心", "通义", "kimi", "Kimi",
|
||||
]
|
||||
|
||||
# 应用商店差评的问题归类。跟 SIGNALS 分开,因为这里的语气是「已经付过钱的人在骂」。
|
||||
REVIEW_ISSUES = {
|
||||
"收费/会员套路": r"会员|收费|付费|太贵|订阅|续费|套路|割韭菜|坑钱|扣费|退款",
|
||||
"打印/排版": r"打印|排版|答题区域|留白|组卷|错序|漏题",
|
||||
"导出/还原": r"导出|下载|PDF|pdf|word|Word|还原|擦除|去字迹|水印|乱码",
|
||||
"识别/准确率": r"识别|认错|不准|错误|错题.*错|转文字|图.*分离|题图",
|
||||
"举一反三": r"举一反三|类似题|相似题|同类型",
|
||||
"功能缺失": r"没有|缺少|不支持|不能|希望增加|什么时候出|搜不到|搜索",
|
||||
"广告/跳转": r"广告|跳转|弹窗|引导",
|
||||
"性能/稳定": r"卡|闪退|崩|打不开|登录不上|慢",
|
||||
"替代/不值": r"免费|豆包|截图|自己就能|没必要|智商税|任何.*软件",
|
||||
}
|
||||
|
||||
STOP = set(
|
||||
"这个 那个 我们 你们 他们 自己 什么 怎么 可以 就是 还是 没有 一个 不是 这样 那样 "
|
||||
"真的 感觉 觉得 知道 现在 时候 已经 因为 所以 但是 如果 然后 而且 他们 东西 一直 "
|
||||
"孩子 家长 小学 老师 谢谢 请问 你好 哈哈 好的 收到 支持 关注 看看 一下 有点".split()
|
||||
)
|
||||
|
||||
|
||||
def load(db_path: Path):
|
||||
con = sqlite3.connect(db_path)
|
||||
con.row_factory = sqlite3.Row
|
||||
notes = [dict(r) for r in con.execute("SELECT * FROM notes")]
|
||||
comments = [dict(r) for r in con.execute("SELECT * FROM comments")]
|
||||
reviews = []
|
||||
try:
|
||||
reviews = [dict(r) for r in con.execute("SELECT * FROM reviews")]
|
||||
except sqlite3.OperationalError:
|
||||
pass # 老库没有 reviews 表,跳过
|
||||
con.close()
|
||||
return notes, comments, reviews
|
||||
|
||||
|
||||
def classify(comments):
|
||||
hit = defaultdict(list)
|
||||
for c in comments:
|
||||
text = c.get("content") or ""
|
||||
for name, pat in SIGNALS.items():
|
||||
if re.search(pat, text):
|
||||
hit[name].append(c)
|
||||
return hit
|
||||
|
||||
|
||||
def top_ngrams(comments, limit=40):
|
||||
cnt = Counter()
|
||||
for c in comments:
|
||||
t = c.get("content") or ""
|
||||
# 只保留中文/字母数字
|
||||
t = re.sub(r"[^\u4e00-\u9fa5a-zA-Z0-9]", " ", t)
|
||||
for seg in t.split():
|
||||
if len(seg) < 2:
|
||||
continue
|
||||
for n in (2, 3, 4):
|
||||
for i in range(len(seg) - n + 1):
|
||||
g = seg[i:i + n]
|
||||
if g in STOP:
|
||||
continue
|
||||
cnt[g] += 1
|
||||
# 去掉被更长词包含且频次接近的碎片
|
||||
items = [(g, v) for g, v in cnt.items() if v >= 2]
|
||||
items.sort(key=lambda x: -x[1])
|
||||
kept = []
|
||||
for g, v in items:
|
||||
if any(g != k and g in k and v <= kv + 1 for k, kv in kept):
|
||||
continue
|
||||
kept.append((g, v))
|
||||
if len(kept) >= limit:
|
||||
break
|
||||
return kept
|
||||
|
||||
|
||||
def hit_issues(text, table):
|
||||
return [name for name, pat in table.items() if re.search(pat, text or "")]
|
||||
|
||||
|
||||
def build_reviews_md(reviews):
|
||||
"""应用商店差评部分:这是「已经付费/安装过的人」的原话,比笔记评论区更接近真相。"""
|
||||
lines = []
|
||||
A = lines.append
|
||||
total = len(reviews)
|
||||
low = [r for r in reviews if (r.get("rating") or 5) <= 2]
|
||||
|
||||
A("## 应用商店差评(竞品实测)\n")
|
||||
A(f"- 样本:**{total}** 条评论,来自 **{len({r.get('app_id') for r in reviews})}** 个竞品")
|
||||
A(f"- 其中 1–2 星:**{len(low)}** 条({len(low) / total * 100:.1f}%)")
|
||||
A("- 采集方式:`python collector/appstore.py`(Apple 公开接口,无需登录)")
|
||||
A("- 局限:接口每页 50 条、最多 10 页,拿不到全量历史,只能看「最近发生了什么」\n")
|
||||
|
||||
# 按 App 汇总
|
||||
per = defaultdict(list)
|
||||
for r in reviews:
|
||||
per[r.get("app_name") or r.get("app_id") or "?"].append(r)
|
||||
A("### 各竞品口碑对比\n")
|
||||
A("| 竞品 | 评论数 | 平均分 | 1–2 星 | 差评率 | 最集中的抱怨 |")
|
||||
A("|---|---:|---:|---:|---:|---|")
|
||||
rows = []
|
||||
for name, items in per.items():
|
||||
n = len(items)
|
||||
avg = sum((i.get("rating") or 0) for i in items) / n if n else 0
|
||||
lows = [i for i in items if (i.get("rating") or 5) <= 2]
|
||||
cnt = Counter()
|
||||
for i in lows:
|
||||
for issue in set(hit_issues((i.get("title") or "") + (i.get("content") or ""), REVIEW_ISSUES)):
|
||||
cnt[issue] += 1
|
||||
top3 = "、".join(f"{k}({v})" for k, v in cnt.most_common(3)) or "-"
|
||||
rows.append((avg, name, n, avg, len(lows), len(lows) / n * 100 if n else 0, top3))
|
||||
for _, name, n, avg, nl, pct, top3 in sorted(rows, reverse=True):
|
||||
A(f"| {name} | {n} | {avg:.2f} | {nl} | {pct:.1f}% | {top3} |")
|
||||
A("")
|
||||
A("> 平均分 4.5 以上还值得看差评,因为**分数是历史累积,差评是这个版本的现状**。\n")
|
||||
|
||||
# 差评问题分布
|
||||
if low:
|
||||
A("### 差评在骂什么(问题词命中,分母 = 全部 1–2 星)\n")
|
||||
A("| 问题 | 条数 | 占差评 |")
|
||||
A("|---|---:|---:|")
|
||||
icnt = Counter()
|
||||
for r in low:
|
||||
for issue in set(hit_issues((r.get("title") or "") + (r.get("content") or ""), REVIEW_ISSUES)):
|
||||
icnt[issue] += 1
|
||||
for name, v in icnt.most_common():
|
||||
A(f"| {name} | {v} | {v / len(low) * 100:.1f}% |")
|
||||
A("")
|
||||
A("> 一条差评可以同时命中多个问题,占比之和会超过 100%。\n")
|
||||
|
||||
# 每个 App 两条最有信息量的差评(按正文长度,长的通常说得具体)
|
||||
A("### 各竞品差评原文(挑最具体的 2 条)\n")
|
||||
for name, items in sorted(per.items(), key=lambda x: -len(x[1])):
|
||||
lows = [i for i in items if (i.get("rating") or 5) <= 2 and len(i.get("content") or "") >= 15]
|
||||
if not lows:
|
||||
continue
|
||||
A(f"**{name}**\n")
|
||||
for r in sorted(lows, key=lambda x: -len(x.get("content") or ""))[:2]:
|
||||
txt = (r.get("title") or "") + "|" + (r.get("content") or "")
|
||||
txt = txt.replace("\n", " ").strip()
|
||||
A(f"- {txt[:220]}")
|
||||
A(f" <sub>{r.get('rating')}★ · v{r.get('version') or '?'} · {r.get('updated') or ''}</sub>")
|
||||
A("")
|
||||
|
||||
# 跨渠道对照:把商店差评问题和小红书信号并排
|
||||
A("### 跨渠道对照:小红书评论 vs 应用商店差评\n")
|
||||
A("| 渠道 | 用户状态 | 这类渠道能证明什么 |")
|
||||
A("|---|---|---|")
|
||||
A("| 小红书评论(笔记评论区) | 有兴趣、问价、观望 | 需求存在、意愿强弱 |")
|
||||
A(f"| 应用商店差评({len(low)} 条 1–2 星) | 已安装、已付费、已失望 | **产品哪里做不好、用户怎么绕过、为什么退款** |")
|
||||
A("")
|
||||
A("> 两个渠道同时出现的抱怨,才是可以立项的需求;只在一边出现的,多半是情绪。\n")
|
||||
return lines
|
||||
|
||||
|
||||
def build_md(notes, comments, out_path: Path, reviews=None):
|
||||
lines = []
|
||||
A = lines.append
|
||||
|
||||
total_like = sum(n.get("liked_count") or 0 for n in notes)
|
||||
A("# 小红书采集分析报告\n")
|
||||
A(f"- 笔记:**{len(notes)}** 篇")
|
||||
A(f"- 评论:**{len(comments)}** 条")
|
||||
A(f"- 笔记总点赞:**{total_like:,}**")
|
||||
kws = Counter(n.get("keyword") or "(未标)" for n in notes)
|
||||
A("- 关键词:" + "、".join(f"{k}({v})" for k, v in kws.most_common()))
|
||||
A("")
|
||||
|
||||
# 互动 Top
|
||||
top = sorted(notes, key=lambda n: (n.get("liked_count") or 0) + (n.get("collected_count") or 0), reverse=True)[:10]
|
||||
if top:
|
||||
A("## 互动 Top 10\n")
|
||||
A("| 标题 | 作者 | 赞 | 藏 | 评 | 藏赞比 | 关键词 |")
|
||||
A("|---|---|---:|---:|---:|---:|---|")
|
||||
for n in top:
|
||||
title = (n.get("title") or "").replace("|", "/")[:30]
|
||||
liked = n.get("liked_count") or 0
|
||||
saved = n.get("collected_count") or 0
|
||||
ratio = f"{saved / liked:.2f}" if liked else "-"
|
||||
A(f"| {title} | {n.get('author_name') or ''} | {liked} | "
|
||||
f"{saved} | {n.get('comment_count') or 0} | {ratio} | {n.get('keyword') or ''} |")
|
||||
A("")
|
||||
A("> 藏赞比 > 1 说明用户是「存下来照着做」而不是「点个赞就走」,收藏尤其值钱。\n")
|
||||
|
||||
# 信号
|
||||
hit = classify(comments)
|
||||
if comments:
|
||||
A("## 需求信号分布\n")
|
||||
A("| 信号 | 条数 | 占比 |")
|
||||
A("|---|---:|---:|")
|
||||
for name, items in sorted(hit.items(), key=lambda x: -len(x[1])):
|
||||
A(f"| {name} | {len(items)} | {len(items) / len(comments) * 100:.1f}% |")
|
||||
A("")
|
||||
A("> 一条评论可以同时命中多个信号,所以占比之和会超过 100%。\n")
|
||||
|
||||
A("## 每类原话(最多 5 条)\n")
|
||||
for name, items in sorted(hit.items(), key=lambda x: -len(x[1])):
|
||||
A(f"### {name}({len(items)} 条)\n")
|
||||
items = sorted(items, key=lambda c: -(c.get("like_count") or 0))[:5]
|
||||
for c in items:
|
||||
txt = (c.get("content") or "").replace("\n", " ").strip()
|
||||
A(f"- {txt[:160]} \n <sub>{c.get('user_name') or '匿名'} · {c.get('ip_location') or ''} · "
|
||||
f"{c.get('like_count') or 0} 赞</sub>")
|
||||
A("")
|
||||
|
||||
# 高赞评论:被顶上去的往往是大家共同的疑问
|
||||
hot = sorted(
|
||||
[c for c in comments if (c.get("like_count") or 0) > 0],
|
||||
key=lambda c: -(c.get("like_count") or 0),
|
||||
)[:10]
|
||||
if hot:
|
||||
A("## 高赞评论 Top 10(往往是共性疑问)\n")
|
||||
A("| 赞 | 评论 | 用户 | IP |")
|
||||
A("|---:|---|---|---|")
|
||||
for c in hot:
|
||||
txt = (c.get("content") or "").replace("\n", " ").replace("|", "/").strip()[:70]
|
||||
A(f"| {c.get('like_count') or 0} | {txt} | {c.get('user_name') or '匿名'} | {c.get('ip_location') or ''} |")
|
||||
A("")
|
||||
|
||||
# 竞品
|
||||
brand_cnt = Counter()
|
||||
for c in comments:
|
||||
for b in BRANDS:
|
||||
if b in (c.get("content") or ""):
|
||||
brand_cnt[b] += 1
|
||||
if brand_cnt:
|
||||
A("## 评论里提到的其他产品\n")
|
||||
for b, v in brand_cnt.most_common():
|
||||
A(f"- **{b}**:{v} 次")
|
||||
A("")
|
||||
|
||||
# 高频词
|
||||
grams = top_ngrams(comments)
|
||||
if grams:
|
||||
A("## 高频词(2–4 字组合,已去停用词)\n")
|
||||
A(" | ".join(f"{g}×{v}" for g, v in grams[:30]))
|
||||
A("")
|
||||
|
||||
if reviews:
|
||||
lines.extend(build_reviews_md(reviews))
|
||||
|
||||
out_path.write_text("\n".join(lines), encoding="utf-8")
|
||||
return out_path
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--db", default=str(ROOT / "data/out/xhs.db"))
|
||||
ap.add_argument("--out", default=str(ROOT / "data/out/report.md"))
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
db = Path(a.db)
|
||||
if not db.exists():
|
||||
print(f"找不到 {db},先跑 analysis/normalize.py")
|
||||
return 1
|
||||
|
||||
notes, comments, reviews = load(db)
|
||||
p = build_md(notes, comments, Path(a.out), reviews)
|
||||
print(f"笔记 {len(notes)} 篇 / 评论 {len(comments)} 条 / 应用商店评论 {len(reviews)} 条 → {p}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,186 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,279 @@
|
||||
"""把采集到的 JSONL 整理成 CSV + SQLite,方便直接分析。
|
||||
|
||||
用法:
|
||||
python analysis/normalize.py
|
||||
python analysis/normalize.py --raw data/raw --out data/out
|
||||
|
||||
只依赖标准库。Windows 下 CSV 用 utf-8-sig,Excel 直接双击打开不乱码。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import json
|
||||
import sqlite3
|
||||
import sys
|
||||
from datetime import datetime, timezone, timedelta
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
CST = timezone(timedelta(hours=8))
|
||||
|
||||
NOTE_FIELDS = [
|
||||
"note_id", "keyword", "title", "desc", "author_id", "author_name",
|
||||
"liked_count", "collected_count", "comment_count", "shared_count",
|
||||
"note_type", "publish_time", "ip_location", "tags", "url",
|
||||
]
|
||||
|
||||
COMMENT_FIELDS = [
|
||||
"note_id", "comment_id", "parent_id", "user_id", "user_name",
|
||||
"content", "like_count", "sub_comment_count", "create_time", "ip_location", "url",
|
||||
]
|
||||
|
||||
# App Store 评论(collector/appstore.py 产出)
|
||||
REVIEW_FIELDS = [
|
||||
"review_id", "app_id", "app_name", "country", "rating",
|
||||
"title", "content", "version", "author", "updated", "keyword", "url",
|
||||
]
|
||||
|
||||
|
||||
def ts_to_str(v):
|
||||
if v in (None, "", 0):
|
||||
return ""
|
||||
try:
|
||||
n = float(v)
|
||||
except (TypeError, ValueError):
|
||||
return str(v)
|
||||
if n > 1e12: # 毫秒
|
||||
n /= 1000
|
||||
try:
|
||||
return datetime.fromtimestamp(n, CST).strftime("%Y-%m-%d %H:%M")
|
||||
except (OverflowError, OSError, ValueError):
|
||||
return str(v)
|
||||
|
||||
|
||||
def read_records(raw_dir: Path):
|
||||
records = []
|
||||
for f in sorted(raw_dir.glob("*.jsonl")):
|
||||
with f.open("r", encoding="utf-8") as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
records.append(json.loads(line))
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
return records
|
||||
|
||||
|
||||
def merge_notes(records):
|
||||
notes = {}
|
||||
for r in records:
|
||||
if r.get("type") not in ("note_card", "note_detail"):
|
||||
continue
|
||||
nid = r.get("note_id")
|
||||
if not nid:
|
||||
continue
|
||||
cur = notes.setdefault(nid, {"note_id": nid, "keyword": r.get("keyword", "")})
|
||||
for k in NOTE_FIELDS:
|
||||
if k in ("note_id", "keyword", "url"):
|
||||
continue
|
||||
v = r.get(k)
|
||||
if v in (None, "", []):
|
||||
continue
|
||||
if k in ("liked_count", "collected_count", "comment_count", "shared_count"):
|
||||
# 取最大值,避免后到的空数据覆盖
|
||||
try:
|
||||
v = max(int(v), int(cur.get(k) or 0))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
cur[k] = v
|
||||
for n in notes.values():
|
||||
n["url"] = f"https://www.xiaohongshu.com/explore/{n['note_id']}"
|
||||
n["publish_time"] = ts_to_str(n.get("publish_time"))
|
||||
if isinstance(n.get("tags"), list):
|
||||
n["tags"] = ",".join(str(t) for t in n["tags"])
|
||||
return list(notes.values())
|
||||
|
||||
|
||||
def merge_comments(records, notes_by_id):
|
||||
seen = {}
|
||||
for r in records:
|
||||
if r.get("type") != "comment":
|
||||
continue
|
||||
cid = r.get("comment_id")
|
||||
if not cid or cid in seen:
|
||||
continue
|
||||
nid = r.get("note_id") or ""
|
||||
note = notes_by_id.get(nid, {})
|
||||
seen[cid] = {
|
||||
"note_id": nid,
|
||||
"comment_id": cid,
|
||||
"parent_id": r.get("parent_id") or "",
|
||||
"user_id": r.get("user_id") or "",
|
||||
"user_name": r.get("user_name") or "",
|
||||
"content": (r.get("content") or "").replace("\n", " ").strip(),
|
||||
"like_count": r.get("like_count") if r.get("like_count") is not None else "",
|
||||
"sub_comment_count": r.get("sub_comment_count") if r.get("sub_comment_count") is not None else "",
|
||||
"create_time": ts_to_str(r.get("create_time")),
|
||||
"ip_location": r.get("ip_location") or "",
|
||||
"url": f"https://www.xiaohongshu.com/explore/{nid}" if nid else "",
|
||||
}
|
||||
_ = note
|
||||
return list(seen.values())
|
||||
|
||||
|
||||
def merge_reviews(records):
|
||||
"""App Store 评论:按 review_id 去重(同一条评论可能在多次采集里重复出现)。"""
|
||||
seen = {}
|
||||
for r in records:
|
||||
if r.get("type") != "review":
|
||||
continue
|
||||
rid = r.get("review_id")
|
||||
if not rid or rid in seen:
|
||||
continue
|
||||
row = {}
|
||||
for k in REVIEW_FIELDS:
|
||||
v = r.get(k)
|
||||
if k == "rating":
|
||||
try:
|
||||
row[k] = int(v)
|
||||
except (TypeError, ValueError):
|
||||
row[k] = None
|
||||
continue
|
||||
if k in ("title", "content", "author", "app_name", "keyword", "version"):
|
||||
row[k] = (v or "").replace("\n", " ").strip()
|
||||
else:
|
||||
row[k] = v if v is not None else ""
|
||||
seen[rid] = row
|
||||
return list(seen.values())
|
||||
|
||||
|
||||
def write_csv(path: Path, rows, fields):
|
||||
with path.open("w", encoding="utf-8-sig", newline="") as fh:
|
||||
w = csv.DictWriter(fh, fieldnames=fields, extrasaction="ignore")
|
||||
w.writeheader()
|
||||
for r in rows:
|
||||
w.writerow({k: r.get(k, "") for k in fields})
|
||||
|
||||
|
||||
def write_db(path: Path, notes, comments, reviews):
|
||||
if path.exists():
|
||||
path.unlink()
|
||||
con = sqlite3.connect(path)
|
||||
cur = con.cursor()
|
||||
cur.execute(
|
||||
"""CREATE TABLE notes(
|
||||
note_id TEXT PRIMARY KEY, keyword TEXT, title TEXT, desc TEXT,
|
||||
author_id TEXT, author_name TEXT,
|
||||
liked_count INTEGER, collected_count INTEGER, comment_count INTEGER,
|
||||
shared_count INTEGER, note_type TEXT, publish_time TEXT,
|
||||
ip_location TEXT, tags TEXT, url TEXT)"""
|
||||
)
|
||||
cur.execute(
|
||||
"""CREATE TABLE comments(
|
||||
comment_id TEXT PRIMARY KEY, note_id TEXT, parent_id TEXT,
|
||||
user_id TEXT, user_name TEXT, content TEXT,
|
||||
like_count INTEGER, sub_comment_count INTEGER,
|
||||
create_time TEXT, ip_location TEXT, url TEXT)"""
|
||||
)
|
||||
cur.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS reviews(
|
||||
review_id TEXT PRIMARY KEY, app_id TEXT, app_name TEXT, country TEXT,
|
||||
rating INTEGER, title TEXT, content TEXT, version TEXT,
|
||||
author TEXT, updated TEXT, keyword TEXT, url TEXT)"""
|
||||
)
|
||||
# 显式列名,避免建表顺序和字段列表不一致时把值塞错列
|
||||
cur.executemany(
|
||||
f"INSERT OR REPLACE INTO notes ({','.join(NOTE_FIELDS)}) "
|
||||
f"VALUES ({','.join('?' * len(NOTE_FIELDS))})",
|
||||
[[n.get(k) for k in NOTE_FIELDS] for n in notes],
|
||||
)
|
||||
cur.executemany(
|
||||
f"INSERT OR REPLACE INTO comments ({','.join(COMMENT_FIELDS)}) "
|
||||
f"VALUES ({','.join('?' * len(COMMENT_FIELDS))})",
|
||||
[[c.get(k) for k in COMMENT_FIELDS] for c in comments],
|
||||
)
|
||||
cur.execute("CREATE INDEX idx_notes_kw ON notes(keyword)")
|
||||
cur.execute("CREATE INDEX idx_comments_note ON comments(note_id)")
|
||||
if reviews:
|
||||
cur.executemany(
|
||||
f"INSERT OR REPLACE INTO reviews ({','.join(REVIEW_FIELDS)}) "
|
||||
f"VALUES ({','.join('?' * len(REVIEW_FIELDS))})",
|
||||
[[r.get(k) for k in REVIEW_FIELDS] for r in reviews],
|
||||
)
|
||||
cur.execute("CREATE INDEX idx_reviews_app ON reviews(app_id)")
|
||||
con.commit()
|
||||
con.close()
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--raw", default=str(ROOT / "data/raw"))
|
||||
ap.add_argument("--out", default=str(ROOT / "data/out"))
|
||||
a = ap.parse_args(argv)
|
||||
|
||||
raw_dir = Path(a.raw)
|
||||
out_dir = Path(a.out)
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if not raw_dir.exists():
|
||||
print(f"找不到原始目录:{raw_dir}")
|
||||
return 1
|
||||
|
||||
records = read_records(raw_dir)
|
||||
if not records:
|
||||
print(f"{raw_dir} 里没有 *.jsonl 数据,先跑采集。")
|
||||
return 1
|
||||
|
||||
notes = merge_notes(records)
|
||||
by_id = {n["note_id"]: n for n in notes}
|
||||
comments = merge_comments(records, by_id)
|
||||
reviews = merge_reviews(records)
|
||||
|
||||
write_csv(out_dir / "notes.csv", notes, NOTE_FIELDS)
|
||||
write_csv(out_dir / "comments.csv", comments, COMMENT_FIELDS)
|
||||
if reviews:
|
||||
write_csv(out_dir / "reviews.csv", reviews, REVIEW_FIELDS)
|
||||
write_db(out_dir / "xhs.db", notes, comments, reviews)
|
||||
|
||||
print(f"原始记录 {len(records)} 条 → 笔记 {len(notes)} 篇 / 评论 {len(comments)} 条 / "
|
||||
f"应用商店评论 {len(reviews)} 条")
|
||||
print(f" {out_dir / 'notes.csv'}")
|
||||
print(f" {out_dir / 'comments.csv'}")
|
||||
if reviews:
|
||||
print(f" {out_dir / 'reviews.csv'}")
|
||||
print(f" {out_dir / 'xhs.db'}")
|
||||
|
||||
# 按关键词看看覆盖面
|
||||
stat = {}
|
||||
for n in notes:
|
||||
stat.setdefault(n.get("keyword") or "(未标)", [0, 0])
|
||||
stat[n.get("keyword") or "(未标)"][0] += 1
|
||||
for c in comments:
|
||||
n = by_id.get(c["note_id"], {})
|
||||
k = n.get("keyword") or "(未标)"
|
||||
stat.setdefault(k, [0, 0])
|
||||
stat[k][1] += 1
|
||||
print("\n关键词 笔记 评论")
|
||||
for k, (a1, a2) in sorted(stat.items(), key=lambda x: -x[1][0]):
|
||||
print(f"{k:<14}{a1:>5}{a2:>7}")
|
||||
|
||||
if reviews:
|
||||
print("\nApp 评论 1-2星")
|
||||
per = {}
|
||||
for r in reviews:
|
||||
key = r.get("app_name") or r.get("app_id") or "?"
|
||||
per.setdefault(key, [0, 0])
|
||||
per[key][0] += 1
|
||||
if (r.get("rating") or 5) <= 2:
|
||||
per[key][1] += 1
|
||||
for k, (c1, c2) in sorted(per.items(), key=lambda x: -x[1][0]):
|
||||
print(f"{k:<16}{c1:>4}{c2:>7}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user