Files
cuotibiye/analysis/normalize.py
T

280 lines
9.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""把采集到的 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())