#!/usr/bin/env python3 """从 Friends 全季剧本(fangj.github.io/friends)提取「表达 / 功能语」并入库。 求真务实:下面是一份**功能语清单**,每条都用 Friends 全季语料**逐条验证**, 只保留真正出现过的(并把出现次数写进 context 作为证据)。 - kind = "expression",function = 功能标签,source = "friends:fangj" - id = e-<5位数字>(不含 0,出现越多号越小),status = "new" - level 由短语中「最难的词」的考试级别推得(查 items 的 word 表) 用法: python actions/import_friends.py """ from __future__ import annotations import datetime as _dt import glob import html import re import sys from pathlib import Path ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(Path(__file__).resolve().parent)) import langdb # noqa: E402 from import_wordlists import no0_numbers # noqa: E402 CORPUS = ROOT / "actions" / "raw" / "friends" LEVELS = ["小学", "中考", "高考", "CET4", "CET6", "考研", "TOEFL", "GRE"] ORDER = {n: i for i, n in enumerate(LEVELS)} # phrase||function (功能标签) SEED = """ i mean||话语标记 you know||话语标记 you see||话语标记 kind of||话语标记 sort of||话语标记 you know what||话语标记 if you know what i mean||话语标记 know what i mean||话语标记 the thing is||话语标记 the point is||话语标记 what i mean is||话语标记 or something||话语标记 or whatever||话语标记 and stuff||话语标记 and everything||话语标记 and all that||话语标记 don't get me wrong||话语标记 no offense||话语标记 by the way||转题 speaking of which||转题 that reminds me||转题 come to think of it||转题 as a matter of fact||强调 in fact||强调 i guess||不确定 i suppose||不确定 i bet||不确定 i wonder||不确定 i'm not sure||不确定 i'm afraid||不确定 i have no idea||不确定 who knows||不确定 god knows||不确定 beats me||不确定 as far as i know||不确定 yeah||附和 yep||附和 yup||附和 sure||附和 exactly||附和 absolutely||附和 totally||附和 definitely||附和 of course||附和 for sure||附和 you bet||附和 i know||附和 i agree||附和 tell me about it||附和 no kidding||附和 you're telling me||附和 i hear you||附和 same here||附和 me too||附和 that's right||附和 that's true||附和 good point||附和 fair enough||附和 sounds good||附和 sounds great||附和 works for me||附和 count me in||附和 why not||附和 sure thing||附和 no problem||礼貌 my pleasure||礼貌 you're welcome||礼貌 no way||反对 not really||反对 i don't think so||反对 i doubt it||反对 come on||催促 give me a break||反对 are you kidding||反对 are you serious||反对 you've got to be kidding||反对 yeah right||反对 whatever||反对 forget it||结束话题 never mind||结束话题 no thanks||礼貌 i'd rather not||反对 not a chance||反对 over my dead body||反对 that's not fair||反对 mind your own business||反对 knock it off||制止 cut it out||制止 stop it||制止 excuse me||注意 guess what||注意 check this out||注意 look at this||注意 pardon||请求重复 pardon me||请求重复 come again||请求重复 say what||请求重复 what did you say||请求重复 what was that||请求重复 what do you mean||请求重复 how come||提问 what for||提问 since when||质疑 who cares||无所谓 what's up||问候 what's going on||提问 what's the matter||关心 what's wrong||关心 what happened||提问 unless||条件 in case||条件 as long as||条件 so long as||条件 if only||条件 even if||条件 whether or not||条件 suppose||条件 what if||条件 if i were you||条件 if you ask me||条件 if you don't mind||条件 if you say so||条件 in that case||条件 otherwise||条件 or else||条件 provided that||条件 even though||转折 although||转折 though||转折 however||转折 whereas||转折 on the other hand||转折 then again||转折 that said||转折 on second thought||转折 all the same||让步 besides||递进 what's more||递进 on top of that||递进 not to mention||递进 in addition||递进 furthermore||递进 let alone||递进 to make matters worse||递进 better yet||递进 for example||举例 for instance||举例 such as||举例 let's say||举例 in other words||举例 that is||举例 first of all||时序 at first||时序 to begin with||时序 after that||时序 afterward||时序 meanwhile||时序 in the meantime||时序 at the same time||时序 sooner or later||时序 eventually||时序 in the end||时序 at last||时序 all of a sudden||时序 right away||时序 in a minute||时序 in a second||时序 from now on||时序 once in a while||时序 every now and then||时序 for a while||时序 in the long run||时序 thanks a lot||礼貌 thank you so much||礼貌 i'm sorry||礼貌 i apologize||礼貌 forgive me||礼貌 do you mind||礼貌 would you mind||礼貌 after you||礼貌 go ahead||礼貌 bless you||礼貌 congratulations||礼貌 good luck||礼貌 take care||礼貌 nice to meet you||礼貌 how are you||礼貌 how's it going||礼貌 how do you do||礼貌 have a nice day||礼貌 see you later||礼貌 see you soon||礼貌 good morning||礼貌 good night||礼貌 happy birthday||礼貌 oh my god||感叹 oh my||感叹 oh god||感叹 my god||感叹 for god's sake||感叹 oh no||感叹 oh yeah||感叹 oh boy||感叹 oh well||感叹 oh dear||感叹 wow||感叹 whoa||感叹 jeez||感叹 geez||感叹 damn||感叹 damn it||感叹 crap||感叹 shoot||感叹 ugh||感叹 oops||感叹 thank god||感叹 what the hell||感叹 what the heck||感叹 holy cow||感叹 hold on||推进 hang on||推进 hold it||推进 wait a minute||推进 wait a second||推进 wait up||推进 give me a second||推进 let me see||推进 let me think||推进 let's see||推进 go on||推进 hurry up||推进 shut up||制止 be quiet||制止 calm down||安抚 take it easy||安抚 take your time||安抚 slow down||安抚 cheer up||安抚 grow up||制止 wake up||催促 sit down||动作 stand up||动作 come over||动作 go away||动作 get out||动作 get up||动作 give up||动作 move on||推进 skip it||结束话题 drop it||结束话题 where were we||推进 my turn||推进 your turn||推进 up to you||推进 a little||程度 a lot||程度 a bit||程度 a couple of||数量 a piece of||数量 a bunch of||数量 a lot of||数量 plenty of||数量 tons of||数量 at least||程度 at most||程度 at all||程度 at times||频率 at the moment||时间 for good||时间 for real||强调 for now||时间 for once||频率 in general||概括 in particular||强调 in public||场合 in private||场合 in person||场合 in advance||时间 in time||时间 on time||时间 on purpose||意图 out of the blue||习语 out of control||习语 out of the question||习语 no wonder||习语 no big deal||习语 big deal||习语 make sense||习语 make sure||习语 make up your mind||习语 take a look||动作 take a break||动作 take a seat||动作 have a look||动作 have fun||习语 good for you||鼓励 way to go||鼓励 nice work||鼓励 well done||鼓励 my bad||承认 fair enough||接受 sounds like a plan||接受 long story short||习语 easier said than done||习语 better late than never||习语 no pain no gain||习语 piece of cake||习语 speak of the devil||习语 what's done is done||习语 so far so good||习语 first things first||习语 last but not least||习语 catch you later||礼貌 take it or leave it||习语 i'm out||习语 i'm in||附和 i'm on it||回应 i'm not buying it||反对 don't mention it||礼貌 what a shame||感叹 what a coincidence||感叹 no offense taken||回应 it depends||回应 depends on||回应 no idea||不确定 i'll see||回应 we'll see||回应 let me know||请求 keep in touch||礼貌 hit me||回应 you wish||反对 in your dreams||反对 dream on||反对 get lost||制止 buzz off||制止 chill out||安抚 hang out||动作 show up||动作 turn up||动作 end up||动作 figure out||动作 freak out||动作 check out||动作 find out||动作 work out||动作 point out||动作 run out||动作 put up with||动作 look forward to||动作 come up with||动作 get along||动作 get over||动作 get through||动作 take over||动作 look up||动作 look into||动作 hold up||动作 mess up||动作 screw up||动作 bring up||动作 break up||动作 make out||动作 turn out||动作 call off||动作 put off||动作 give in||动作 give it a shot||鼓励 give it a try||鼓励 take a chance||鼓励 play it cool||习语 keep it down||制止 knock on wood||习语 fingers crossed||习语 no hard feelings||和好 let bygones be bygones||和好 """ def strip_tags(s: str) -> str: s = re.sub(r"(?s)<[^>]+>", " ", s) return html.unescape(s).replace("\u2019", "'").replace("\u2018", "'") def load_corpus() -> list[str]: parts = [] for f in glob.glob(str(CORPUS / "season" / "*.html")): t = strip_tags(Path(f).read_text(encoding="latin-1")) for line in re.split(r"[\n\r]+", t): line = line.strip() if not line: continue line = re.sub(r"^[A-Za-z][A-Za-z .'\-]{0,20}:\s*", "", line) line = re.sub(r"\[[^\]]*\]", " ", line) line = re.sub(r"\([^)]*\)", " ", line) line = re.sub(r"\s+", " ", line).strip() if line: parts.append(line) return [p.lower() for p in parts] # ---- 挖掘:短语动词(词频驱动,非人工清单) ---- VERBS = set("""get go come take give make put look hold hang turn keep figure freak check end find feel work point run show bring break call cut drop fall pick pull push set shut sit stand stay stick throw try wake watch wear write pass pay play move mess screw blow calm carry cheer clean close count deal eat fix follow grow hand head help hit knock lay leave let lie light meet mix open pack read ride ring roll rush save see sell send sign slow sort speak split start step stop switch talk tear tell think tie touch use wait walk warm wash act add agree allow answer appear argue arrive ask avoid bear beat beg behave believe belong bend bet bind bite blame block boil book bother bother bounce bow breathe brush burn burst bury buy cancel care cast catch cause chase chat cheat chew chop claim clear climb cling collect combine compare complain complete concentrate confess confirm confuse connect consider consist contain continue convince cook cool cope copy correct cost cough cover crash crawl create cross cry cure curl damage dance dare decide declare defend delay deliver demand deny depend describe deserve design destroy develop die dig direct disagree disappear discover discuss divide doubt drag draw dream dress drink drive dry dump earn employ encourage enjoy enter escape examine exchange excuse exercise exist expand expect explain explode explore express extend face fail fancy fasten fear fetch fight fill fit flash flee float flow fly fold force forget forgive form freeze gain gather glance grab greet guess guide handle happen harm hate heal heat hesitate hide hire hop hope hug hunt hurry hurt ignore imagine impress improve include increase influence inform insist inspire install intend interrupt introduce invent invite involve join joke judge jump kick kiss kneel land last laugh launch lead leak lean leap learn lend lift limit link list live load lock lose love lower mark marry match matter measure melt mention mind miss notice obey observe obtain occur offer operate order organize owe own pack paint park perform permit persuade phone pick place plant please plug polish pour practice praise pray prefer prepare present preserve press pretend prevent print produce promise pronounce protect prove provide publish pull punch punish purchase pursue question quit race raise reach realize receive recognize recommend record recover reduce refer reflect refuse regret reject relax release rely remain remember remind remove repair repeat replace reply report represent request rescue research resist respect respond rest retire return reveal review reward rob rub ruin rule sail satisfy scare scatter schedule score scratch scream search secure seek seem select separate serve settle sew shake shape share shave shine shock shoot shout shove sigh sing sink skip sleep slide slip smell smoke solve sound spare spell spill spin spit spoil spot spread squeeze stare steal steer stir stretch strike struggle study stuff succeed suffer suggest suit supply support suppose surprise survive swallow swear sweep swim swing tap taste tease tempt test thank threaten tidy tip tolerate translate travel treat trick trip trust twist type understand unite vary visit volunteer vote wander warn waste wave weigh welcome whisper wipe wonder worry wrap yell""".split()) PART = set("up out off on in down over away back through along around about across ahead apart aside forth forward together under".split()) # 真正常接小品词的常见动词(精确,避免 book about 之类假阳性) COREV = set("""get go come take give make put look hold hang turn keep figure freak check end find feel work point run show bring break call cut drop fall pick pull push set shut sit stand stay stick throw try wake watch wear write pass pay play move mess screw blow calm carry cheer clean close count deal eat fix follow grow hand head help hit knock lay leave let lie light meet mix open pack read ride ring roll save see sell send sign slow sort speak split start step stop switch talk tear tell think tie touch use wait walk warm wash ask back beat catch draw dress jump join kick live pull settle shake step stick sweep throw""".split()) PREP = set("with to of for from about on in into at".split()) PRO = set("it that this him her them me you us one".split()) # 挖掘假阳性(动词+介词的非固定搭配)手剔 BLACK = { "back in", "back on", "back over", "deal about", "feel about", "find in", "hand up", "head on", "look under", "play in", "play on", "ring on", "see about", "see in", "set on", "sit in", "sit on", "stop on", "talk in", "think on", "walk over", "walk up", "walk in", "live in", "live on", "live together", "run down", "look in", "look down", "jump out", "jump up", "start out", "hand on", "head in", "head up", "head down", "go across", "work in", } def mine_phrasal(utts: list[str], names: set[str], pmi_min: float = 7.0): import math from collections import Counter c2, c3, cp = Counter(), Counter(), Counter() uni = Counter() toks = [] for u in utts: t = re.findall(r"[a-z]+(?:'[a-z]+)?", u) toks.append(t) uni.update(t) N = sum(uni.values()) def pmi(g, n): den = 1.0 for w in g.split(): den *= uni[w] / N return math.log2((n / N) / den) if den > 0 else 0 for t in toks: for i in range(len(t) - 1): if t[i] in COREV and t[i+1] in PART: c2[f"{t[i]} {t[i+1]}"] += 1 for i in range(len(t) - 2): if t[i] in COREV and t[i+1] in PART and t[i+2] in PREP: c3[f"{t[i]} {t[i+1]} {t[i+2]}"] += 1 out = {} for g, n in list(c2.items()) + list(c3.items()): th = 4 if g.count(" ") == 1 else 3 if n >= th and not any(w in names for w in g.split()): out[g] = max(n, out.get(g, 0)) return out def main() -> int: for st in (sys.stdout, sys.stderr): try: st.reconfigure(encoding="utf-8") except (AttributeError, ValueError): pass utts = load_corpus() text = "\n".join(utts) seed = [] seen = set() for ln in SEED.strip().splitlines(): if "||" not in ln: continue p, fn = ln.split("||", 1) p = p.strip().lower() if p and p not in seen: seen.add(p) seed.append((p, fn.strip())) # 逐条验证出现次数 rows = [] for phrase, fn in seed: cnt = len(re.findall(r"\b" + re.escape(phrase).replace(r"\ ", r"\s+") + r"\b", text)) if cnt > 0: rows.append({"phrase": phrase, "fn": fn, "count": cnt}) rows.sort(key=lambda r: (-r["count"], r["phrase"])) # 挖掘短语动词(首词限于常见动词,故不会命中专名) mined = {g: n for g, n in mine_phrasal(utts, set()).items() if g not in BLACK} have = {r["phrase"] for r in rows} for g, n in sorted(mined.items(), key=lambda x: -x[1]): if g not in have: rows.append({"phrase": g, "fn": "短语动词", "count": n}) rows.sort(key=lambda r: (-r["count"], r["phrase"])) # 中文译文(人工维护) zh = {} zhf = ROOT / "actions" / "raw" / "friends_expr_zh.tsv" if zhf.exists(): for ln in zhf.read_text(encoding="utf-8").splitlines(): if "\t" in ln: a, b = ln.split("\t", 1) zh[a.strip().lower()] = b.strip() # 用 word 表推 level(取短语里最难的词) conn = langdb.connect() wl = {r["item"]: r["level"] for r in conn.execute( "SELECT item, level FROM items WHERE kind='word' AND source LIKE 'wordlist:%'")} today = _dt.date.today().isoformat() nums = no0_numbers() items = [] for r in rows: lv = "" for w in re.findall(r"[a-z]+", r["phrase"]): if w in wl and wl[w] in ORDER: if not lv or ORDER[wl[w]] > ORDER[lv]: lv = wl[w] items.append({ "id": "e-" + next(nums), "kind": "expression", "item": r["phrase"], "level": lv, "meaning": zh.get(r["phrase"], ""), "context": "", "status": "new", "first": "", "fix": "", "function": r["fn"], "tags": "口语," + r["fn"], "source": "friends:fangj", "added": today, "hits": 0, "streak": 0, "next_review": None, }) removed = conn.execute("DELETE FROM items WHERE source LIKE 'friends:%'").rowcount n = langdb.ingest(conn, {"items": items}) conn.close() print(f"清单 {len(seed)} 条 → 语料验证通过 {len(rows)} 条(≥1 次)") print(f"清除旧朋友条目 {removed},导入 {n['items']};id {items[0]['id']} → {items[-1]['id']}") print("Top10:", [(r['phrase'], r['count']) for r in rows[:10]]) return 0 if __name__ == "__main__": sys.exit(main())