Files
ai-crm/apps/server/docs/pdd/clean_scraped_md.py
T
2026-10-21 23:23:48 +08:00

314 lines
9.2 KiB
Python
Executable File
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.
#!/usr/bin/env python3
"""清理拼多多开放平台文档抓取污染。
处理内容:
1. 将「一行一个代码块 + 行号」合并为完整代码块
2. 去掉 xxxxxxxxxx 占位、行号、零宽字符 / 不间断空格
3. 去掉「点击收起」「点击展开」等页面交互文案
4. 去掉仅含空内容的「### API工具」小节
用法:
python clean_scraped_md.py # 交互选择
python clean_scraped_md.py --all # 处理目录下全部 md
python clean_scraped_md.py a.md b.md # 指定文件(相对本脚本目录或绝对路径)
python clean_scraped_md.py --dry-run --all
"""
from __future__ import annotations
import argparse
import re
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parent
NUM_LINE = re.compile(r"^\d+\s*$")
UI_TOGGLE = re.compile(r"^(点击收起|点击展开)\s*$")
EMPTY_API_TOOLS = re.compile(r"\n### API工具\s*$")
MULTI_BLANK = re.compile(r"\n{3,}")
TAB_LABEL = re.compile(r"^(JAVA|CURL|JSON|XML)\s*$", re.I)
def list_md_files() -> list[Path]:
"""列出本目录下全部 md,相对 ROOT 排序。"""
files = sorted(ROOT.rglob("*.md"), key=lambda p: str(p.relative_to(ROOT)))
return [p for p in files if p.is_file()]
def resolve_targets(raw: list[str]) -> list[Path]:
"""把用户输入的路径解析为绝对路径。"""
out: list[Path] = []
for item in raw:
p = Path(item)
if not p.is_absolute():
cand = (ROOT / p).resolve()
if not cand.exists():
cand = Path.cwd().joinpath(p).resolve()
p = cand
else:
p = p.resolve()
if not p.is_file() or p.suffix.lower() != ".md":
raise FileNotFoundError(f"不是有效的 md 文件: {item}")
out.append(p)
return out
def normalize_content(s: str) -> str:
"""规范化代码行:nbsp→空格,纯零宽行→空行。"""
s = s.replace("\xa0", " ").replace("\u00a0", " ")
if "\u200b" in s and s.strip("\u200b").strip() == "":
return ""
return s.replace("\u200b", "")
def is_xxxx_placeholder(s: str) -> bool:
t = s.strip()
return bool(t) and set(t) <= {"x"} and len(t) >= 4
def merge_polluted_fences(text: str) -> str:
"""合并抓取产生的单行代码块序列。"""
raw = text.split("\n")
n = len(raw)
out: list[str] = []
i = 0
def is_fence(idx: int) -> bool:
return idx < n and raw[idx].strip() == "```"
while i < n:
if not is_fence(i):
line = raw[i]
if "\u200b" in line or "\xa0" in line:
if "\u200b" in line and line.strip("\u200b").strip() == "":
out.append("")
else:
out.append(line.replace("\xa0", " ").replace("\u200b", ""))
else:
out.append(line)
i += 1
continue
# 解析当前 fence
j = i + 1
content_lines: list[str] = []
while j < n and raw[j].strip() != "```":
content_lines.append(raw[j])
j += 1
if j >= n:
out.append(raw[i])
i += 1
continue
# 已是多行代码块,保持原样
if len(content_lines) > 1:
out.extend(raw[i : j + 1])
i = j + 1
continue
content = content_lines[0] if content_lines else ""
# 跳过 xxxxxxxxxx 占位及其后的行号
if is_xxxx_placeholder(content):
k = j + 1
while k < n and (raw[k].strip() == "" or NUM_LINE.match(raw[k].strip())):
k += 1
i = k
continue
seq_start = i
code_parts: list[str] = []
cur = i
end = j + 1
while is_fence(cur):
j2 = cur + 1
cl: list[str] = []
while j2 < n and raw[j2].strip() != "```":
cl.append(raw[j2])
j2 += 1
if j2 >= n or len(cl) > 1:
break
c = cl[0] if cl else ""
if not is_xxxx_placeholder(c):
code_parts.append(normalize_content(c))
k = j2 + 1
while k < n and (raw[k].strip() == "" or NUM_LINE.match(raw[k].strip())):
k += 1
if is_fence(k):
pj = k + 1
pcl: list[str] = []
while pj < n and raw[pj].strip() != "```":
pcl.append(raw[pj])
pj += 1
if pj < n and len(pcl) <= 1:
cur = k
end = k
continue
end = k
break
had_numbers = any(
NUM_LINE.match(raw[t].strip()) for t in range(seq_start, min(end, n))
)
if len(code_parts) >= 2 or (len(code_parts) == 1 and had_numbers):
out.append("```")
out.extend(code_parts)
out.append("```")
i = end
continue
out.extend(raw[i : j + 1])
i = j + 1
return "\n".join(out)
def polish_fences(text: str) -> str:
"""整理代码块内外空白。"""
def repl(m: re.Match[str]) -> str:
body = m.group(1).strip("\n")
return f"```\n{body}\n```"
text = re.sub(r"```\n(.*?)```", repl, text, flags=re.S)
text = re.sub(r"```\n(#{1,6} )", r"```\n\n\1", text)
return text
def strip_ui_noise(text: str) -> str:
"""去掉点击收起/展开、语言 Tab 标签、空 API工具 小节。"""
lines = text.split("\n")
kept: list[str] = []
for line in lines:
if UI_TOGGLE.match(line) or TAB_LABEL.match(line):
continue
kept.append(line)
text = "\n".join(kept)
text = EMPTY_API_TOOLS.sub("\n", text)
text = MULTI_BLANK.sub("\n\n", text)
return text.rstrip() + "\n"
def clean_markdown(text: str) -> str:
"""对单份文档做完整清理。"""
text = merge_polluted_fences(text)
text = polish_fences(text)
text = strip_ui_noise(text)
return text
def interactive_select(files: list[Path]) -> list[Path]:
"""终端交互多选 md 文件。"""
if not files:
print("未找到任何 .md 文件。")
return []
print(f"目录: {ROOT}")
print("可选文档(输入序号,逗号/空格分隔;a=全部;q=退出):\n")
for idx, path in enumerate(files, 1):
rel = path.relative_to(ROOT)
print(f" {idx:3d}. {rel}")
print()
raw = input("> ").strip()
if not raw or raw.lower() in {"q", "quit", "exit"}:
return []
if raw.lower() in {"a", "all", "*"}:
return files
tokens = re.split(r"[\s,,]+", raw)
selected: list[Path] = []
for tok in tokens:
if not tok:
continue
if not tok.isdigit():
print(f"无效输入: {tok}", file=sys.stderr)
return []
num = int(tok)
if num < 1 or num > len(files):
print(f"序号越界: {num}", file=sys.stderr)
return []
selected.append(files[num - 1])
# 保序去重
seen: set[Path] = set()
uniq: list[Path] = []
for p in selected:
if p not in seen:
seen.add(p)
uniq.append(p)
return uniq
def process_file(path: Path, *, dry_run: bool) -> bool:
"""处理单个文件;有实质改动返回 True。"""
original = path.read_text(encoding="utf-8")
cleaned = clean_markdown(original)
rel = path.relative_to(ROOT) if path.is_relative_to(ROOT) else path
# 仅补文件末尾换行不算实质改动,避免反复误报
if cleaned.rstrip("\n") == original.rstrip("\n"):
print(f" skip {rel}(无需清理)")
return False
stats = (
f"lines {original.count(chr(10))}→{cleaned.count(chr(10))}, "
f"fences {original.count('```')}→{cleaned.count('```')}"
)
if dry_run:
print(f" dry {rel}({stats})")
return True
path.write_text(cleaned, encoding="utf-8")
print(f" ok {rel}({stats})")
return True
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(description="清理拼多多文档抓取污染")
parser.add_argument(
"paths",
nargs="*",
help="要处理的 md(相对 docs/pdd 或绝对路径);省略则交互选择",
)
parser.add_argument("--all", action="store_true", help="处理目录下全部 md")
parser.add_argument(
"--dry-run",
action="store_true",
help="只预览改动统计,不写回文件",
)
args = parser.parse_args(argv)
all_md = list_md_files()
try:
if args.all:
targets = all_md
elif args.paths:
targets = resolve_targets(args.paths)
else:
targets = interactive_select(all_md)
except FileNotFoundError as e:
print(str(e), file=sys.stderr)
return 1
if not targets:
print("未选择文件。")
return 0
print(("预览" if args.dry_run else "处理") + f" {len(targets)} 个文件:")
changed = 0
for path in targets:
if process_file(path, dry_run=args.dry_run):
changed += 1
print(f"完成:改动 {changed}/{len(targets)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())