103 lines
3.2 KiB
Python
103 lines
3.2 KiB
Python
#!/usr/bin/env python3
|
|
"""用 Friends 全季剧本给 items 回填上下文例句(context)。
|
|
|
|
- 单词:按词元索引直接命中。
|
|
- 词组/表达:按最稀有的词定位候选句,再整串匹配。
|
|
- 只填空 context 的项(可重复运行)。
|
|
|
|
用法:
|
|
python actions/fill_context.py
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import glob
|
|
import html
|
|
import re
|
|
import sqlite3
|
|
import sys
|
|
from collections import defaultdict
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parent.parent
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
import langdb # noqa: E402
|
|
|
|
CORPUS = ROOT / "actions" / "raw" / "friends"
|
|
SPK = re.compile(r"^\s*([A-Za-z][A-Za-z .'\-]{0,20}):\s*(.+)$")
|
|
|
|
|
|
def strip_tags(s: str) -> str:
|
|
s = re.sub(r"(?s)<[^>]+>", " ", s)
|
|
return html.unescape(s).replace("\u2019", "'").replace("\u2018", "'")
|
|
|
|
|
|
def load_sentences() -> list[str]:
|
|
out = []
|
|
for f in glob.glob(str(CORPUS / "season" / "*.html")):
|
|
text = strip_tags(Path(f).read_text(encoding="latin-1")) # 先去标签再切行
|
|
for line in re.split(r"[\n\r]+", text):
|
|
m = SPK.match(line.strip())
|
|
if not m:
|
|
continue
|
|
d = m.group(2)
|
|
d = re.sub(r"\[[^\]]*\]", " ", d)
|
|
d = re.sub(r"\([^)]*\)", " ", d)
|
|
d = re.sub(r"\s+", " ", d).strip()
|
|
if 4 <= len(d) <= 240:
|
|
out.append(d)
|
|
return out
|
|
|
|
|
|
def main() -> int:
|
|
for st in (sys.stdout, sys.stderr):
|
|
try:
|
|
st.reconfigure(encoding="utf-8")
|
|
except (AttributeError, ValueError):
|
|
pass
|
|
|
|
sents = load_sentences()
|
|
low = [s.lower() for s in sents]
|
|
post: dict[str, list[int]] = defaultdict(list)
|
|
for i, s in enumerate(low):
|
|
for w in set(re.findall(r"[a-z]+(?:'[a-z]+)?", s)):
|
|
post[w].append(i)
|
|
print(f"例句库: {len(sents)} 句;词索引: {len(post)}")
|
|
|
|
conn = langdb.connect()
|
|
rows = conn.execute(
|
|
"SELECT id, kind, item FROM items WHERE context IS NULL OR context='' "
|
|
"OR context LIKE 'Friends 全季%'").fetchall()
|
|
n = 0
|
|
for r in rows:
|
|
item = (r["item"] or "").strip().lower()
|
|
if not item:
|
|
continue
|
|
toks = re.findall(r"[a-z]+(?:'[a-z]+)?", item)
|
|
if not toks:
|
|
continue
|
|
hit = None
|
|
if len(toks) == 1:
|
|
lst = post.get(toks[0])
|
|
if lst:
|
|
hit = lst[0]
|
|
else:
|
|
# 选最稀有的词定位候选
|
|
pivot = min(toks, key=lambda w: len(post.get(w, ())))
|
|
pat = re.compile(r"(?<![a-z])" + re.escape(item).replace(r"\ ", r"\s+") + r"(?![a-z])")
|
|
for i in post.get(pivot, [])[:2000]:
|
|
if pat.search(low[i]):
|
|
hit = i
|
|
break
|
|
if hit is not None:
|
|
conn.execute("UPDATE items SET context=? WHERE id=?", (sents[hit], r["id"]))
|
|
n += 1
|
|
conn.commit()
|
|
filled = conn.execute("SELECT COUNT(*) FROM items WHERE context IS NOT NULL AND context<>''").fetchone()[0]
|
|
conn.close()
|
|
print(f"回填 {n} 条;有例句的 items 共 {filled}")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|