File size: 17,623 Bytes
4bba76c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 | """
英文基礎講義 960 單字全量解析與建置工具
產出:data/english960.json (全部 960 字,含音標、詞性、繁體中文釋義、例句與例句中譯、變形 forms)
"""
import glob
import io
import json
import os
import re
import sys
from opencc import OpenCC
sys.stdout.reconfigure(encoding='utf-8')
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
OCR_DIR = os.path.join(ROOT, 'scratch', 'ocr')
OUT_FILE = os.path.join(ROOT, 'data', 'english960.json')
cc = OpenCC('s2twp')
# 常見標準詞性對照
POS_NORM = {
'名': '名', '名词': '名', '名詞': '名',
'動': '動', '动': '動', '动词': '動', '動詞': '動',
'形': '形', '形容': '形', '形容词': '形', '形容詞': '形',
'副': '副', '副词': '副', '副詞': '副',
'介': '介', '介词': '介', '介詞': '介',
'連': '連', '连': '連', '连词': '連', '連詞': '連',
'代': '代', '代词': '代', '代詞': '代',
'感': '感', '感叹': '感', '感嘆': '感',
'數': '數', '数': '數',
'冠': '冠', '冠词': '冠',
}
# 960 常用標準不規則動詞三態字典
IRREGULAR_VERBS = {
'be': ('was/were', 'been'),
'have': ('had', 'had'),
'do': ('did', 'done'),
'say': ('said', 'said'),
'go': ('went', 'gone'),
'get': ('got', 'gotten'),
'make': ('made', 'made'),
'know': ('knew', 'known'),
'think': ('thought', 'thought'),
'take': ('took', 'taken'),
'see': ('saw', 'seen'),
'come': ('came', 'come'),
'find': ('found', 'found'),
'give': ('gave', 'given'),
'tell': ('told', 'told'),
'feel': ('felt', 'felt'),
'leave': ('left', 'left'),
'put': ('put', 'put'),
'mean': ('meant', 'meant'),
'keep': ('kept', 'kept'),
'let': ('let', 'let'),
'begin': ('began', 'begun'),
'show': ('showed', 'shown'),
'hear': ('heard', 'heard'),
'run': ('ran', 'run'),
'bring': ('brought', 'brought'),
'write': ('wrote', 'written'),
'sit': ('sat', 'sat'),
'stand': ('stood', 'stood'),
'lose': ('lost', 'lost'),
'pay': ('paid', 'paid'),
'meet': ('met', 'met'),
'set': ('set', 'set'),
'learn': ('learned', 'learned'),
'lead': ('led', 'led'),
'understand': ('understood', 'understood'),
'speak': ('spoke', 'spoken'),
'read': ('read', 'read'),
'spend': ('spent', 'spent'),
'grow': ('grew', 'grown'),
'win': ('won', 'won'),
'teach': ('taught', 'taught'),
'buy': ('bought', 'bought'),
'send': ('sent', 'sent'),
'build': ('built', 'built'),
'fall': ('fell', 'fallen'),
'cut': ('cut', 'cut'),
'sell': ('sold', 'sold'),
'drive': ('drove', 'driven'),
'break': ('broke', 'broken'),
'hit': ('hit', 'hit'),
'eat': ('ate', 'eaten'),
'catch': ('caught', 'caught'),
'draw': ('drew', 'drawn'),
'choose': ('chose', 'chosen'),
'fight': ('fought', 'fought'),
'throw': ('threw', 'thrown'),
'wear': ('wore', 'worn'),
'fly': ('flew', 'flown'),
'drink': ('drank', 'drunk'),
'forget': ('forgot', 'forgotten'),
'sing': ('sang', 'sung'),
'hide': ('hid', 'hidden'),
'ride': ('rode', 'ridden'),
'sleep': ('slept', 'slept'),
'bite': ('bit', 'bitten'),
'burn': ('burned', 'burned'),
'blow': ('blew', 'blown'),
'shake': ('shook', 'shaken'),
'swim': ('swam', 'swum'),
'ring': ('rang', 'rung'),
'rise': ('rose', 'risen'),
'feed': ('fed', 'fed'),
'shut': ('shut', 'shut'),
'cost': ('cost', 'cost'),
'hurt': ('hurt', 'hurt'),
'wake': ('woke', 'woken'),
'become': ('became', 'become'),
'overcome': ('overcame', 'overcome'),
'forgive': ('forgave', 'forgiven'),
'mistake': ('mistook', 'mistaken'),
'shake': ('shook', 'shaken'),
'sweep': ('swept', 'swept'),
'hold': ('held', 'held'),
'leave': ('left', 'left'),
'lend': ('lent', 'lent'),
'dig': ('dug', 'dug'),
'hang': ('hung', 'hung'),
'shine': ('shone', 'shone'),
'shoot': ('shot', 'shot'),
'steal': ('stole', 'stolen'),
'strike': ('struck', 'struck'),
'tear': ('tore', 'torn'),
'wear': ('wore', 'worn'),
'freeze': ('froze', 'frozen'),
'bear': ('bore', 'born'),
'lay': ('laid', 'laid'),
'lie': ('lay', 'lain'),
}
# OCR 中文校正對照表(常見字形辨識偏差)
ZH_CLEANUP = {
'成': '成為',
'碓定': '確定',
'使興巒': '使興奮',
'偷霜': '偷竊',
'摆': '選擇',
'恤衫': '襯衫',
'衫': '襯衫',
'周題': '問題',
'周题': '問題',
'方案': '專案、計劃',
'夏慮': '憂慮',
'撸心': '擔心',
'德到': '聽到',
}
# 常用不規則名詞複數
IRREGULAR_NOUNS = {
'person': 'people',
'man': 'men',
'woman': 'women',
'child': 'children',
'foot': 'feet',
'tooth': 'teeth',
'goose': 'geese',
'mouse': 'mice',
'fish': 'fish',
'sheep': 'sheep',
'deer': 'deer',
'life': 'lives',
'leaf': 'leaves',
'half': 'halves',
'knife': 'knives',
'wife': 'wives',
'wolf': 'wolves',
'city': 'cities',
'family': 'families',
'baby': 'babies',
'story': 'stories',
'country': 'countries',
'party': 'parties',
'body': 'bodies',
'strawberry': 'strawberries',
'lady': 'ladies',
}
# 常用不規則形容詞比較級與最高級
IRREGULAR_ADJS = {
'good': ('better', 'best'),
'bad': ('worse', 'worst'),
'far': ('farther', 'farthest'),
'little': ('less', 'least'),
'many': ('more', 'most'),
'much': ('more', 'most'),
}
# 少數 OCR 缺損單字之後備釋義與音標
FALLBACK_WORDS = {
'from': {'pos': '介', 'zh': '來自、從', 'ipa': '[frɑm]'},
'parent': {'pos': '名', 'zh': '雙親之一、父親或母親', 'ipa': '[ˋpɛrənt]'},
'hear': {'pos': '動', 'zh': '聽見、得知', 'ipa': '[hɪr]'},
'since': {'pos': '介', 'zh': '自從…以來、因為', 'ipa': '[sɪns]'},
'hand': {'pos': '名', 'zh': '手、指針;(動)交給', 'ipa': '[hænd]'},
'either': {'pos': '代', 'zh': '兩者之一;(副)也(不)', 'ipa': '[ˋiðɚ]'},
'mistake': {'pos': '名', 'zh': '錯誤、過失', 'ipa': '[mɪsˋtek]'},
'glass': {'pos': '名', 'zh': '玻璃杯、玻璃', 'ipa': '[glæs]'},
'back': {'pos': '名', 'zh': '背部;(副)向後、回原處', 'ipa': '[bæk]'},
'price': {'pos': '名', 'zh': '價格、價錢', 'ipa': '[praɪs]'},
'apple': {'pos': '名', 'zh': '蘋果', 'ipa': '[ˋæp!]'},
'son': {'pos': '名', 'zh': '兒子', 'ipa': '[sʌn]'},
'Friday': {'pos': '名', 'zh': '星期五', 'ipa': '[ˋfraɪde]'},
'pocket': {'pos': '名', 'zh': '口袋', 'ipa': '[ˋpɑkɪt]'},
'player': {'pos': '名', 'zh': '選手、運動員、球員', 'ipa': '[ˋpleɚ]'},
'chicken': {'pos': '名', 'zh': '雞肉、小雞', 'ipa': '[ˋtʃɪkɪn]'},
'snow': {'pos': '名', 'zh': '雪;(動)下雪', 'ipa': '[sno]'},
'bedroom': {'pos': '名', 'zh': '臥室、睡房', 'ipa': '[ˋbɛdˌrum]'},
'large': {'pos': '形', 'zh': '大的、巨大的', 'ipa': '[lɑrdʒ]'},
'low': {'pos': '形', 'zh': '低的、矮的', 'ipa': '[lo]'},
'clock': {'pos': '名', 'zh': '時鐘', 'ipa': '[klɑk]'},
'block': {'pos': '名', 'zh': '街區、大樓;(動)阻擋', 'ipa': '[blɑk]'},
'pear': {'pos': '名', 'zh': '梨子', 'ipa': '[pɛr]'},
}
def clean_word(w):
return re.sub(r'[^a-zA-Z\-\s\']', '', w).strip()
def build_forms(word, pos, book_form=None):
if book_form:
return book_form
w_low = word.lower()
# 動詞
if pos == '動':
if w_low in IRREGULAR_VERBS:
past, pp = IRREGULAR_VERBS[w_low]
return {'type': 'verb', 'past': past, 'pp': pp, 'src': 'gen'}
else:
# 規則變化
if w_low.endswith('e'):
past = w_low + 'd'
pp = w_low + 'd'
elif w_low.endswith('y') and len(w_low) > 1 and w_low[-2] not in 'aeiou':
past = w_low[:-1] + 'ied'
pp = w_low[:-1] + 'ied'
else:
past = w_low + 'ed'
pp = w_low + 'ed'
return {'type': 'verb', 'past': past, 'pp': pp, 'src': 'gen'}
# 名詞
elif pos == '名':
if w_low in IRREGULAR_NOUNS:
return {'type': 'noun', 'plural': IRREGULAR_NOUNS[w_low], 'src': 'gen'}
else:
# 規則名詞複數
if w_low.endswith(('s', 'x', 'z', 'ch', 'sh')):
pl = w_low + 'es'
elif w_low.endswith('y') and len(w_low) > 1 and w_low[-2] not in 'aeiou':
pl = w_low[:-1] + 'ies'
elif w_low.endswith('f'):
pl = w_low[:-1] + 'ves'
elif w_low.endswith('fe'):
pl = w_low[:-2] + 'ves'
else:
pl = w_low + 's'
return {'type': 'noun', 'plural': pl, 'src': 'gen'}
# 形容詞
elif pos == '形':
if w_low in IRREGULAR_ADJS:
comp, sup = IRREGULAR_ADJS[w_low]
return {'type': 'adj', 'comp': comp, 'super': sup, 'src': 'gen'}
else:
if len(w_low) <= 4:
comp = w_low + ('r' if w_low.endswith('e') else 'er')
sup = w_low + ('st' if w_low.endswith('e') else 'est')
elif w_low.endswith('y'):
comp = w_low[:-1] + 'ier'
sup = w_low[:-1] + 'iest'
else:
comp = 'more ' + w_low
sup = 'most ' + w_low
return {'type': 'adj', 'comp': comp, 'super': sup, 'src': 'gen'}
# 其他詞性
return {'type': pos, 'src': 'gen'}
def extract_page_data(part, r_num, pno, expected_nums):
path = os.path.join(OCR_DIR, part, f'p{pno:03d}.json')
if not os.path.exists(path):
return []
with open(path, 'r', encoding='utf-8') as f:
items = json.load(f)
# 頂部 4 個單字
top_words = []
for it in items[:6]:
t = it['text'].strip()
if ',' in t and not t.startswith('第'):
top_words = [clean_word(w) for w in t.split(',') if clean_word(w)]
break
# 序號位置錨點
anchors = []
num_items = {}
for it in items:
t = it['text'].strip()
if len(t) == 3 and t.isdigit() and int(t) in expected_nums:
num_items[int(t)] = it['box'][1]
for idx, n in enumerate(expected_nums):
if n in num_items:
anchors.append(num_items[n])
else:
anchors.append(350 + idx * 450)
split_ys = [(anchors[i] + anchors[i+1]) / 2 for i in range(3)]
slots = [[], [], [], []]
for it in items:
y = it['box'][1]
if y < 220:
continue
s_idx = 0
for sy in split_ys:
if y > sy:
s_idx += 1
else:
break
slots[s_idx].append(it)
page_words = []
for idx, n in enumerate(expected_nums):
target_word = top_words[idx] if idx < len(top_words) else f"word_{n}"
target_lower = target_word.lower()
slot_items = slots[idx]
slot_texts = [x['text'].strip() for x in slot_items]
# 尋找主定義行
main_line = ''
for t in slot_texts:
if t.startswith('★'): continue
if t.lower().startswith(target_lower) and ('[' in t or '(' in t or '(' in t):
main_line = t
break
if not main_line:
for t in slot_texts:
if t.startswith('★'): continue
if target_lower in t.lower() and any(k in t for k in POS_NORM.keys()):
main_line = t
break
if not main_line:
for t in slot_texts:
if not t.startswith('★') and any(f'({k}' in t or f'({k}' in t for k in POS_NORM.keys()):
main_line = t
break
pos = '名'
if main_line:
for k, v in POS_NORM.items():
if f'({k}' in main_line or f'({k}' in main_line or f'{k})' in main_line or f'{k})' in main_line:
pos = v
break
ipa = ''
if main_line:
m_ipa = re.search(r'\[([^\]]+)\]', main_line)
if not m_ipa:
m_ipa = re.search(r'\[([^\)]+)\)', main_line)
if m_ipa:
ipa = f"[{m_ipa.group(1).strip()}]"
zh = ''
if main_line:
# 找到最後一個詞性標記後面的中文
m_pos_end = re.search(r'[\((][名動形副介連代感數冠][\))]', main_line)
if m_pos_end:
after_pos = main_line[m_pos_end.end():].strip()
after_pos = re.sub(r'^[^\u4e00-\u9fa5\w]+', '', after_pos)
zh = cc.convert(after_pos)
else:
m_ch = re.findall(r'[\u4e00-\u9fa5]+', main_line)
if m_ch:
zh = cc.convert('、'.join(m_ch))
# 應用中文校正對照
for bad_k, good_v in ZH_CLEANUP.items():
if zh == bad_k or zh.startswith(bad_k):
zh = zh.replace(bad_k, good_v, 1)
# 例句尋找
ex = ''
exZh = ''
for t in slot_texts:
if t.startswith('★') or t == main_line:
continue
# 英文例句
if not ex and len(t) > 6 and re.search(r'^[A-Z"\'\‘\“]', t) and not any(k in t for k in ['(動', '(名', '(形', '(副']):
ex = t
# 例句中文翻譯
elif ex and not exZh and re.search(r'[\u4e00-\u9fa5]', t) and not any(k in t for k in ['(動', '(名', '(形', '(副']):
exZh = cc.convert(t)
if n == 339 and not exZh:
exZh = '我的生日在三月。'
elif n == 711 and not exZh:
exZh = '她上個月滿三十歲。'
# 尋找講義筆記變形
book_form = None
for t in slot_texts:
# 動詞三態
m_v3 = re.search(r'([a-zA-Z]+)\s*[--]\s*([a-zA-Z]+)\s*[--]\s*([a-zA-Z]+)', t)
if m_v3 and (m_v3.group(1).lower() == target_lower or '三' in t):
book_form = {
'type': 'verb',
'past': m_v3.group(2).lower(),
'pp': m_v3.group(3).lower(),
'src': 'book'
}
break
# 複數
if '複' in t or '复' in t:
m_pl = re.search(r'([a-zA-Z]+)\s*[\((]?[複复]數', t)
if m_pl:
book_form = {
'type': 'noun',
'plural': m_pl.group(1).lower(),
'src': 'book'
}
break
# 如果提取出的 zh 為空或品質不佳,採用後備精修字典
if target_word in FALLBACK_WORDS:
fb = FALLBACK_WORDS[target_word]
if not zh or len(zh) < 2 or zh.startswith('...'):
zh = fb.get('zh', zh)
if not ipa:
ipa = fb.get('ipa', ipa)
if fb.get('pos'):
pos = fb.get('pos', pos)
# 若例句為空,提供貼合國中基礎的標準語境例句
if not ex:
if pos == '名':
ex = f"This is a {target_word}."
exZh = f"這是一個{zh.split('、')[0]}。"
elif pos == '動':
ex = f"I want to {target_word}."
exZh = f"我想要{zh.split('、')[0]}。"
else:
ex = f"It is very {target_word}."
exZh = f"這非常{zh.split('、')[0]}。"
# 生成語法變形 forms
forms = build_forms(target_word, pos, book_form)
page_words.append({
'n': n,
'word': target_word,
'pos': pos,
'zh': zh,
'ipa': ipa,
'ex': ex,
'exZh': exZh,
'forms': forms,
'part': part,
'round': r_num,
})
return page_words
def build_full_960():
parts_info = [
('A', 1, 1),
('B', 17, 321),
('C', 33, 641),
]
all_words = []
for part, round_start, word_start in parts_info:
for r_idx in range(16):
r_num = round_start + r_idx
base_p = 8 + r_idx * 6
for p_offset in range(5):
pno = base_p + p_offset
expected_nums = [word_start + r_idx * 20 + p_offset * 4 + i for i in range(4)]
p_words = extract_page_data(part, r_num, pno, expected_nums)
all_words.extend(p_words)
# 排序確保序號 1~960
all_words.sort(key=lambda w: w['n'])
# 保留第 1~40 題先前已經精細人工校對的資料
if os.path.exists(OUT_FILE):
with open(OUT_FILE, 'r', encoding='utf-8') as f:
old_data = json.load(f)
old_words = {w['n']: w for w in old_data.get('words', []) if w['n'] <= 40}
for i in range(len(all_words)):
if all_words[i]['n'] in old_words:
all_words[i] = old_words[all_words[i]['n']]
output_data = {
'count': len(all_words),
'words': all_words
}
with open(OUT_FILE, 'w', encoding='utf-8') as f:
json.dump(output_data, f, ensure_ascii=False, indent=2)
print(f"成功建置 {len(all_words)} 個單字題庫!寫入至: {OUT_FILE}")
if __name__ == '__main__':
build_full_960()
|