Coverage for src/wiktextract/extractor/en/linkages.py: 72%

766 statements  

« prev     ^ index     » next       coverage.py v7.18.0, created at 2026-12-03 12:05 +0000

1# Code related to parsing linkages (synonyms, hypernyms, related terms, etc) 

2# 

3# Copyright (c) 2019-2021 Tatu Ylonen. See file LICENSE and https://ylonen.org 

4 

5import re 

6import unicodedata 

7from typing import Optional, Sequence 

8 

9from wikitextprocessor import ( 

10 LevelNode, 

11 NodeKind, 

12 TemplateNode, 

13 WikiNode, 

14) 

15from wikitextprocessor.core import TemplateArgs 

16from wikitextprocessor.parser import ( 

17 HTMLNode, 

18 is_list, 

19 is_list_item, 

20) 

21 

22from ...datautils import ( 

23 data_append, 

24 data_extend, 

25 ns_title_prefix_tuple, 

26 split_at_comma_semi, 

27) 

28from ...page import clean_node, is_panel_template 

29from ...tags import linkage_beginning_tags, valid_tags 

30from ...wxr_context import WiktextractContext 

31from ..ruby import extract_ruby, parse_ruby # noqa: F401 

32from .form_descriptions import ( 

33 classify_desc, 

34 decode_tags, 

35 head_final_bantu_langs, 

36 head_final_bantu_re, 

37 head_final_numeric_langs, 

38 head_final_other_langs, 

39 head_final_other_re, 

40 head_final_re, 

41 parse_head_final_tags, 

42 parse_sense_qualifier, 

43) 

44from .section_titles import TRANSLATIONS_TITLE 

45from .type_utils import FormData, LinkageData, SenseData, WordData 

46 

47# Linkage will be ignored if it matches this regexp before splitting 

48linkage_pre_split_ignore_re = re.compile( 

49 r"^(" 

50 + "|".join( 

51 re.escape(x) 

52 for x in [ 

53 "For more variations, see ", 

54 "Signal flag:", 

55 "Semaphore:", 

56 ] 

57 ) 

58 + r")" 

59) 

60 

61# Linkage will be ignored if it has one of these prefixes 

62linkage_ignore_prefixes = [ 

63 "Historical and regional synonyms of ", 

64 "edit data", 

65 "or these other third-person pronouns", 

66 "introduced in Unicode ", 

67 "Entries in the ", 

68 "Wikipedia article ", 

69 "Wiktionary's coverage of ", 

70 "Ethnologue entry for ", 

71 "Any of Thesaurus:", 

72 "See contents of Category:", 

73 "See also Thesaurus:", 

74 "See also Appendix:", 

75 "see also Appendix:", 

76 "see also Thesaurus:", 

77 "As SMS messaging ", 

78 "For the reversed question mark used in some right-to-left-scripts", 

79 "such as ", 

80 "Appendix:", 

81 "Category:", 

82 ":Category:", 

83] 

84 

85# Linkage will be ignored if it has any of these suffixes 

86linkage_ignore_suffixes = [ 

87 " Wikipedia", 

88 " Wikipedia.", 

89 " edition of Wiktionary", 

90] 

91 

92# Linkage will be ignored if it is one of these (with full match) 

93linkage_ignore_whole = [ 

94 "etc.", 

95 "other derived terms:", 

96 "Formal terms", 

97 "informal and slang terms", 

98] 

99 

100# Linkage will be ignored if it matches this regexp 

101linkage_ignore_re = re.compile( 

102 r"^(" 

103 + "|".join(re.escape(x) for x in linkage_ignore_whole) 

104 + r")$|^(" 

105 + "|".join(re.escape(x) for x in linkage_ignore_prefixes) 

106 + r")|(" 

107 + "|".join(re.escape(x) for x in linkage_ignore_suffixes) 

108 + r")$" 

109) 

110 

111# These prefixes will be removed from linkages, leaving the rest. This is 

112# considered separately for each linkage in a list. 

113linkage_remove_prefixes_re = re.compile( 

114 r"^(" 

115 + r"|".join( 

116 re.escape(x) 

117 for x in [ 

118 ":", 

119 "see Thesaurus:", 

120 "See Thesaurus:", 

121 "see also Thesaurus:", 

122 "See also Thesaurus:", 

123 "see also ", 

124 "See also ", 

125 "see ", 

126 "See ", 

127 "from ", 

128 "abbreviation of ", 

129 "ISO 639-1 code ", 

130 "ISO 639-3 code ", 

131 "Thesaurus:", 

132 ] 

133 ) 

134 + ")" 

135) 

136 

137# When removing prefix from linkage, this dictionary can be used to map 

138# the removed prefix to a space-separated list of tags to add 

139linkage_remove_prefixes_tags = { 

140 "abbreviation of ": "abbreviation", 

141} 

142 

143# These suffixes will be removed from linkages, leaving the rest. This is 

144# considered separately for each linkage in a list. 

145linkage_remove_suffixes_re = re.compile( 

146 r"(\s+on (Wikispecies|Wikimedia Commons|" 

147 r"[A-Z]\w+ Wiktionary|[A-Z]\w+ Wikipedia)\.?|" 

148 r"\s*[-–] Pre-reform orthography.*)" 

149 r"$" 

150) 

151 

152# Ignore linkage parenthesized sections that contain one of these strings 

153linkage_paren_ignore_contains_re = re.compile( 

154 r"\b(" 

155 + "|".join( 

156 re.escape(x) 

157 for x in [ 

158 "from Etymology", 

159 "used as", 

160 "usage notes", 

161 ] 

162 ) 

163 + ")([, ]|$)" 

164) 

165 

166taxonomic_ending_map = { 

167 "superkingdoms": "superkingdom", 

168 "kingdoms": "kingdom", 

169 "subkingdoms": "subkingdom", 

170 "infrakingdoms": "infrakingdom", 

171 "phylums": "phylum", 

172 "subphylums": "subphylum", 

173 "infraphylums": "infraphylum", 

174 "superclasses": "superclass", 

175 "classes": "class", 

176 "orders": "order", 

177 "suborders": "suborder", 

178 "families": "family", 

179 "subfamilies": "subfamily", 

180 "genera": "genus", 

181} 

182for k, v in list(taxonomic_ending_map.items()): 

183 taxonomic_ending_map[v] = v # Also add singular -> singular 

184taxonomic_ending_re = re.compile( 

185 r"\s+[-‐‑‒–—]\s+({})$".format( 

186 "|".join(re.escape(x) for x in taxonomic_ending_map) 

187 ) 

188) 

189 

190# Exceptional splits for linkages. This can be used to fix particular linkages 

191# that are not handled correctly by the default code. This can also be used 

192# to create automatic aliases, e.g., for mapping "..." and "…" to both. 

193linkage_split_exceptions = { 

194 "∛ ∜": ["∛", "∜"], 

195 "...": ["...", "…"], 

196 "…": ["...", "…"], 

197} 

198 

199# Truncate linkage word if it matches any of these strings 

200linkage_truncate_re = re.compile( 

201 "|".join( 

202 re.escape(x) 

203 for x in [ 

204 " and its derived terms", 

205 " UTF-16 0x214C", 

206 ] 

207 ) 

208) 

209 

210# Regexp for identifying special linkages containing lists of letters, digits, 

211# or characters 

212script_chars_re = re.compile( 

213 r"(script letters| script| letters|" 

214 r"Dialectological|Puctuation|Symbols|" 

215 r"Guillemets|Single guillemets|" 

216 r" tetragrams|" 

217 r" digits)(;|$)|" 

218 r"(^|; )(Letters using |Letters of the |" 

219 r"Variations of letter )|" 

220 r"^(Hiragana|Katakana)$" 

221) 

222 

223# Matches an unicode character including any combining diacritics (even if 

224# separate characters) 

225unicode_dc_re = re.compile( 

226 r"\w[{}]|.".format( 

227 "".join( 

228 chr(x) 

229 for x in range(0, 0x110000) 

230 if unicodedata.category(chr(x)) == "Mn" 

231 ) 

232 ) 

233) 

234 

235 

236def extract_alt_form_section( 

237 wxr: WiktextractContext, word_entry: WordData, level_node: LevelNode 

238) -> None: 

239 for list_node in level_node.find_child(NodeKind.LIST): 

240 for list_item in list_node.find_child(NodeKind.LIST_ITEM): 

241 for node in list_item.children: 

242 if isinstance(node, TemplateNode) and node.template_name in [ 

243 "l", 

244 "link", 

245 "L", 

246 "alt", 

247 "alter", 

248 ]: 

249 extract_l_template(wxr, word_entry, node) 

250 elif isinstance(node, WikiNode) and node.kind == NodeKind.LINK: 

251 word = clean_node(wxr, None, node) 

252 if word != "": 252 ↛ 241line 252 didn't jump to line 241 because the condition on line 252 was always true

253 form: FormData = {"form": word, "tags": ["alternative"]} 

254 data_append(word_entry, "forms", form) 

255 

256 

257def extract_l_template( 

258 wxr: WiktextractContext, word_entry: WordData, t_node: TemplateNode 

259) -> None: 

260 forms: list[FormData] = [] 

261 expanded_node = wxr.wtp.parse( 

262 wxr.wtp.node_to_wikitext(t_node), expand_all=True 

263 ) 

264 lang_code = clean_node(wxr, None, t_node.template_parameters.get(1, "")) 

265 for span_tag in expanded_node.find_html("span"): 

266 span_lang = span_tag.attrs.get("lang", "") 

267 span_class = span_tag.attrs.get("class", "") 

268 if span_lang == lang_code: 268 ↛ 273line 268 didn't jump to line 273 because the condition on line 268 was always true

269 word = clean_node(wxr, None, span_tag) 

270 if word != "": 270 ↛ 265line 270 didn't jump to line 265 because the condition on line 270 was always true

271 form: FormData = {"form": word, "tags": ["alternative"]} 

272 forms.append(form) 

273 elif span_lang.endswith("-Latn") and len(forms) > 0: 

274 roman = clean_node(wxr, None, span_tag) 

275 if roman != "": 

276 forms[-1]["roman"] = roman 

277 elif "label-content" in span_class and len(forms) > 0: 

278 tag_text = clean_node(wxr, None, span_tag) 

279 if classify_desc(tag_text) == "tags": 

280 tagsets1, _ = decode_tags(tag_text) 

281 tags: list[str] = [] 

282 for ts in tagsets1: 

283 tags.extend(ts) 

284 for form in forms: 

285 form["tags"].extend(tags) 

286 data_extend(word_entry, "forms", forms) 

287 

288 

289ZH_DIAL_TAGS = { 

290 "Classical Chinese": ["Classical-Chinese"], 

291 "Formal": ["formal"], 

292 "Written Standard Chinese": ["Written-vernacular-Chinese"], 

293 "Northeastern Mandarin": ["Northeastern-Mandarin"], 

294 "Jilu Mandarin": ["Jilu-Mandarin"], 

295 "Jiaoliao Mandarin": ["Jiaoliao-Mandarin"], 

296 "Central Plains Mandarin": ["Central-Plains-Mandarin"], 

297 "Lanyin Mandarin": ["Lanyin-Mandarin"], 

298 "Southwestern Mandarin": ["Southwestern-Mandarin"], 

299 "Jianghuai Mandarin": ["Jianghuai-Mandarin"], 

300 "Northern Min": ["Min-Bei"], 

301 "Eastern Min": ["Min-Dong"], 

302 "Southern Min": ["Min-Nan"], 

303 "Zhongshan Min": ["Zhongshan-Min"], 

304 "Southern Pinghua": ["Southern-Pinghua"], 

305 "Puxian Min": ["Puxian-Min"], 

306} 

307 

308 

309def extract_zh_dial_template( 

310 wxr: WiktextractContext, 

311 word_entry: WordData, 

312 t_node: TemplateNode, 

313 sense: str, 

314): 

315 # https://en.wiktionary.org/wiki/Template:zh-dial 

316 from .pronunciation import split_zh_pron_raw_tag 

317 

318 linkage_list: list[LinkageData] = [] 

319 expanded_node = wxr.wtp.parse( 

320 wxr.wtp.node_to_wikitext(t_node), expand_all=True 

321 ) 

322 for table_node in expanded_node.find_child_recursively(NodeKind.TABLE): 322 ↛ 323line 322 didn't jump to line 323 because the loop on line 322 never started

323 is_note_row = False 

324 note_tags = {} 

325 for row_node in table_node.find_child(NodeKind.TABLE_ROW): 

326 for cell_node in row_node.find_child( 

327 NodeKind.TABLE_HEADER_CELL | NodeKind.TABLE_CELL 

328 ): 

329 if cell_node.kind == NodeKind.TABLE_HEADER_CELL: 

330 is_note_row = clean_node(wxr, None, cell_node) == "Note" 

331 elif is_note_row: 

332 for note_str in clean_node(wxr, None, cell_node).split(";"): 

333 if "-" in note_str: 

334 note_symbol, note = note_str.split("-", maxsplit=1) 

335 note_symbol = note_symbol.strip() 

336 note = note.strip() 

337 if note_symbol != "" and note != "": 

338 note_tags[note_symbol] = note 

339 lang_tags = [] 

340 region_tags = [] 

341 for row_node in table_node.find_child(NodeKind.TABLE_ROW): 

342 if not row_node.contain_node(NodeKind.TABLE_CELL): 

343 continue # skip header row 

344 for header_node in row_node.find_child(NodeKind.TABLE_HEADER_CELL): 

345 lang_tags = split_zh_pron_raw_tag( 

346 clean_node(wxr, None, header_node) 

347 ) 

348 if lang_tags == ["Note"]: # skip last note row 

349 continue 

350 for cell_node in row_node.find_child(NodeKind.TABLE_CELL): 

351 for link_node in cell_node.find_child(NodeKind.LINK): 

352 region_tags = split_zh_pron_raw_tag( 

353 clean_node(wxr, None, link_node) 

354 ) 

355 for span_tag in cell_node.find_html("span"): 

356 span_text = clean_node(wxr, None, span_tag) 

357 if span_text == "": 

358 continue 

359 if ( 

360 span_tag.attrs.get("lang", "") == "zh" 

361 and span_text != wxr.wtp.title 

362 ): 

363 l_data: LinkageData = {"word": span_text} 

364 if sense != "": 

365 l_data["sense"] = sense 

366 if len(lang_tags) > 0: 

367 data_extend(l_data, "raw_tags", lang_tags) 

368 if len(region_tags) > 0: 

369 data_extend(l_data, "raw_tags", region_tags) 

370 linkage_list.append(l_data) 

371 elif ( 

372 span_tag.attrs.get("style", "") == "font-size:60%" 

373 and len(linkage_list) > 0 

374 ): 

375 for note_symbol in span_text.split(","): 

376 note_symbol = note_symbol.strip() 

377 raw_tag = note_symbol 

378 if note_symbol in note_tags: 

379 raw_tag = note_tags[note_symbol] 

380 if raw_tag != "": 

381 data_append( 

382 linkage_list[-1], "raw_tags", raw_tag 

383 ) 

384 

385 for l_data in linkage_list: 

386 raw_tags = [] 

387 for raw_tag in l_data.get("raw_tags", []): 

388 if raw_tag in ZH_DIAL_TAGS: 

389 data_extend(l_data, "tags", ZH_DIAL_TAGS[raw_tag]) 

390 elif raw_tag in valid_tags: 

391 data_append(l_data, "tags", raw_tag) 

392 else: 

393 raw_tags.append(raw_tag) 

394 if len(raw_tags) > 0: 

395 l_data["raw_tags"] = raw_tags 

396 elif "raw_tags" in l_data: 

397 del l_data["raw_tags"] 

398 data_extend(word_entry, "synonyms", linkage_list) 

399 

400 

401def extract_nv_root_terms_template( 

402 wxr: WiktextractContext, 

403 word_entry: WordData, 

404 linkage_type: str, 

405 t_node: TemplateNode, 

406) -> None: 

407 # https://en.wiktionary.org/wiki/Template:nv-root-terms 

408 # The term list comes from `#categorytree`, which isn't implemented, 

409 # so keep the category name for users to collate. 

410 category = f"Navajo terms belonging to the root {wxr.wtp.title}" 

411 root_sense = clean_node(wxr, None, t_node.template_parameters.get(1, "")) 

412 if root_sense != "": 412 ↛ 414line 412 didn't jump to line 414 because the condition on line 412 was always true

413 category += f" ({root_sense})" 

414 data_append(word_entry, linkage_type, {"source": "Category:" + category}) 

415 

416 

417def parse_linkage( 

418 wxr: WiktextractContext, 

419 data: WordData, 

420 field: str, 

421 linkagenode: LevelNode, 

422 word: str, 

423 sense_datas: list[SenseData], 

424 is_reconstruction: bool, 

425) -> None: 

426 assert isinstance(data, dict) 

427 assert isinstance(field, str) 

428 assert isinstance(linkagenode, LevelNode) 

429 # print("field", field) 

430 # print("data", data) 

431 # print("children:") 

432 if not wxr.config.capture_linkages: 432 ↛ 433line 432 didn't jump to line 433 because the condition on line 432 was never true

433 return 

434 have_panel_template = False 

435 

436 def linkage_template_fn1(name: str, ht: TemplateArgs) -> Optional[str]: 

437 nonlocal have_panel_template 

438 if is_panel_template(wxr, name): 

439 have_panel_template = True 

440 return "" 

441 # Ignore auto-filled templates like Template:table:Solar System/en 

442 if name.startswith(("table:", "list:")): 

443 return "" 

444 return None 

445 

446 # Main body of parse_linkage() 

447 l_nodes: list[str | WikiNode] = [] 

448 l_sense = "" 

449 for node in linkagenode.children: 

450 if isinstance(node, TemplateNode) and node.template_name == "zh-dial": 

451 extract_zh_dial_template(wxr, data, node, l_sense) 

452 elif ( 

453 isinstance(node, TemplateNode) 

454 and node.template_name == "nv-root-terms" 

455 ): 

456 extract_nv_root_terms_template(wxr, data, field, node) 

457 elif isinstance(node, WikiNode) and node.kind == NodeKind.LIST: 

458 for list_item in node.find_child(NodeKind.LIST_ITEM): 

459 for t_node in list_item.find_child(NodeKind.TEMPLATE): 

460 if t_node.template_name in ["s", "sense"]: 

461 l_sense = clean_node(wxr, None, t_node).strip("(): ") 

462 l_nodes.append(node) 

463 else: 

464 l_nodes.append(node) 

465 text = wxr.wtp.node_to_wikitext(l_nodes) 

466 parsed = wxr.wtp.parse( 

467 text, expand_all=True, template_fn=linkage_template_fn1 

468 ) 

469 

470 text_outside_list_items = parse_linkage_recurse( 

471 wxr, 

472 parsed.children, 

473 field, 

474 None, 

475 None, 

476 word, 

477 data, 

478 sense_datas, 

479 is_reconstruction, 

480 ) 

481 

482 if not data.get(field) and not have_panel_template: 

483 text = "".join(text_outside_list_items).strip() 

484 if "\n" not in text and "," in text and text.count(",") > 3: 

485 if not text.startswith("See "): 485 ↛ exitline 485 didn't return from function 'parse_linkage' because the condition on line 485 was always true

486 parse_linkage_item( 

487 wxr, 

488 [text], 

489 field, 

490 word, 

491 data, 

492 sense_datas, 

493 is_reconstruction, 

494 None, 

495 ) 

496 

497 

498def parse_linkage_recurse( 

499 wxr: WiktextractContext, 

500 contents: list[WikiNode | str], 

501 field: str, 

502 sense: str | None, 

503 block_header_sense: str | None, 

504 word: str, 

505 data, 

506 sense_datas, 

507 is_reconstruction, 

508) -> list[str]: 

509 assert isinstance(contents, (list, tuple)) 

510 assert sense is None or isinstance(sense, str) 

511 # print("PARSE_LINKAGE_RECURSE: {}: {}".format(sense, contents)) 

512 

513 # Return values 

514 text_outside_list_items: list[str] = [] 

515 

516 for node in contents: 

517 if isinstance(node, str): 

518 # Ignore top-level text, generally comments before the 

519 # linkages list. However, if no linkages are found, then 

520 # use this for linkages (not all words use bullet points 

521 # for linkages). 

522 text_outside_list_items.append(node) 

523 continue 

524 assert isinstance(node, WikiNode) 

525 kind = node.kind 

526 # print("PARSE_LINKAGE_RECURSE CHILD", kind) 

527 if is_list(node) or kind in (NodeKind.TABLE, NodeKind.TABLE_ROW): 

528 toli = parse_linkage_recurse( 

529 wxr, 

530 node.children, 

531 field, 

532 sense, 

533 block_header_sense, 

534 word, 

535 data, 

536 sense_datas, 

537 is_reconstruction, 

538 ) 

539 text_outside_list_items.extend(toli) 

540 elif is_list_item(node) or kind == NodeKind.TABLE_CELL: 

541 v = parse_linkage_item( 

542 wxr, 

543 node.children, 

544 field, 

545 word, 

546 data, 

547 sense_datas, 

548 is_reconstruction, 

549 sense, 

550 ) 

551 if v is not None: 551 ↛ 516line 551 didn't jump to line 516 because the condition on line 551 was always true

552 # parse_linkage_item() can return a value that should 

553 # be used as the sense for the follow-on linkages, 

554 # which are typically provided in a table (see 滿) 

555 block_header_sense = "".join(v) 

556 elif kind in ( 

557 NodeKind.TABLE_CAPTION, 

558 NodeKind.TABLE_HEADER_CELL, 

559 NodeKind.PREFORMATTED, 

560 NodeKind.BOLD, 

561 ): 

562 # Let's still ignore table extra stuff 

563 continue 

564 elif isinstance(node, HTMLNode): 564 ↛ 566line 564 didn't jump to line 566 because the condition on line 564 was never true

565 # Recurse to process inside the HTML for most tags 

566 if node.sarg in ("gallery", "ref", "cite", "caption"): 

567 continue 

568 classes = (node.attrs.get("class") or "").replace("+", " ").split() 

569 if "qualifier-content" in classes: 

570 sense1 = clean_node(wxr, None, node.children) 

571 if sense1.endswith(":"): 

572 sense1 = sense1[:-1].strip() 

573 if sense and sense1: 

574 wxr.wtp.debug( 

575 "linkage qualifier-content on multiple " 

576 "levels: {!r} and {!r}".format(sense, sense1), 

577 sortid="page/2170", 

578 ) 

579 toli = parse_linkage_recurse( 

580 wxr, 

581 node.children, 

582 field, 

583 sense1, 

584 block_header_sense, 

585 word, 

586 data, 

587 sense_datas, 

588 is_reconstruction, 

589 ) 

590 text_outside_list_items.extend(toli) 

591 elif "list-switcher-header" in classes: 

592 block_header_sense = clean_node(wxr, None, node.children) 

593 if block_header_sense.endswith(":"): 

594 block_header_sense = block_header_sense[:-1].strip() 

595 elif any(x in classes for x in ("NavFrame", "term-list")): 

596 # NavFrame uses previously assigned block_header_sense 

597 # (from a "(sense):" item) and clears it afterwards 

598 # print(f"{sense=}, {block_header_sense=}") 

599 toli = parse_linkage_recurse( 

600 wxr, 

601 node.children, 

602 field, 

603 sense or block_header_sense, 

604 block_header_sense, 

605 word, 

606 data, 

607 sense_datas, 

608 is_reconstruction, 

609 ) 

610 text_outside_list_items.extend(toli) 

611 block_header_sense = None 

612 else: 

613 toli = parse_linkage_recurse( 

614 wxr, 

615 node.children, 

616 field, 

617 sense, 

618 block_header_sense, 

619 word, 

620 data, 

621 sense_datas, 

622 is_reconstruction, 

623 ) 

624 text_outside_list_items.extend(toli) 

625 elif isinstance(node, LevelNode): 625 ↛ 627line 625 didn't jump to line 627 because the condition on line 625 was never true

626 # Just recurse to any possible subsections 

627 toli = parse_linkage_recurse( 

628 wxr, 

629 node.children, 

630 field, 

631 sense, 

632 block_header_sense, 

633 word, 

634 data, 

635 sense_datas, 

636 is_reconstruction, 

637 ) 

638 text_outside_list_items.extend(toli) 

639 elif kind in (NodeKind.BOLD, NodeKind.ITALIC): 

640 # Skip these on top level; at least sometimes bold is 

641 # used for indicating a subtitle 

642 continue 

643 elif kind == NodeKind.LINK: 643 ↛ 660line 643 didn't jump to line 660 because the condition on line 643 was always true

644 # Recurse into the last argument 

645 # Apparently ":/" is used as a link to "/", so strip 

646 # initial value 

647 toli = parse_linkage_recurse( 

648 wxr, 

649 node.largs[-1], 

650 field, 

651 sense, 

652 block_header_sense, 

653 word, 

654 data, 

655 sense_datas, 

656 is_reconstruction, 

657 ) 

658 text_outside_list_items.extend(toli) 

659 else: 

660 wxr.wtp.debug( 

661 "parse_linkage_recurse unhandled {}: {}".format(kind, node), 

662 sortid="page/2196", 

663 ) 

664 

665 return text_outside_list_items 

666 

667 

668def parse_linkage_item( 

669 wxr: WiktextractContext, 

670 contents: list[str | WikiNode], 

671 field: str, 

672 word: str, 

673 data: WordData, 

674 sense_datas: list[SenseData], 

675 is_reconstruction: bool, 

676 sense: str | None = None, 

677) -> list[str]: 

678 assert isinstance(contents, (list, tuple)) 

679 assert isinstance(field, str) 

680 assert sense is None or isinstance(sense, str) 

681 

682 # print("PARSE_LINKAGE_ITEM: {} ({}): {}" 

683 # .format(field, sense, contents)) 

684 

685 parts: list[str] = [] 

686 ruby: list[tuple[str, str]] = [] 

687 urls: list[str] = [] 

688 # data about link text; this is used to skip splitting on 

689 # linkage text items that contain stuff like commas; for 

690 # example "Hunde, die bellen, beißen nicht" in article 

691 # beißen is split into "Hunde", "die bellen" etc. 

692 # We take that link text and use it, eventually, 

693 # in split_at_comma_semi to skip splitting on those 

694 # commas. 

695 links_that_should_not_be_split: list[str] = [] 

696 

697 def item_recurse( 

698 contents: list[str | WikiNode], possible_sense: str | None = None 

699 ) -> bool: 

700 assert isinstance(contents, (list, tuple)) 

701 nonlocal sense 

702 nonlocal ruby 

703 nonlocal parts 

704 is_sense = False 

705 # print("ITEM_RECURSE:", contents) 

706 for node in contents: 

707 if isinstance(node, str): 

708 parts.append(node) 

709 continue 

710 kind = node.kind 

711 # print( 

712 # "ITEM_RECURSE KIND:", 

713 # kind, 

714 # node.sarg if node.sarg else node.largs, 

715 # ) 

716 

717 #### parts into possible_sense 

718 if ( 

719 is_list_item(node) 

720 or is_list(node) 

721 or kind 

722 in ( 

723 NodeKind.TABLE, 

724 NodeKind.TABLE_ROW, 

725 NodeKind.TABLE_CELL, 

726 ) 

727 and parts 

728 ): 

729 # print(f"{parts=}") 

730 candidate_sense: str | None 

731 candidate_sense = clean_node(wxr, None, parts) 

732 is_sense = False 

733 

734 if candidate_sense.endswith(":"): 

735 is_sense = True 

736 candidate_sense = candidate_sense[:-1].strip() 

737 if candidate_sense.startswith("(") and candidate_sense.endswith( 737 ↛ 740line 737 didn't jump to line 740 because the condition on line 737 was never true

738 ")" 

739 ): 

740 is_sense = True 

741 candidate_sense = candidate_sense[1:-1].strip() 

742 if ( 

743 candidate_sense.lower() == TRANSLATIONS_TITLE 

744 or not is_sense 

745 ): 

746 candidate_sense = None 

747 # print(f"{possible_sense=}, {is_sense=}") 

748 if is_sense: 

749 possible_sense = candidate_sense 

750 parts = [] 

751 else: 

752 candidate_sense = None 

753 

754 # Handle nodes 

755 if is_list_item(node): 755 ↛ 756line 755 didn't jump to line 756 because the condition on line 755 was never true

756 parse_linkage_item( 

757 wxr, 

758 node.children, 

759 field, 

760 word, 

761 data, 

762 sense_datas, 

763 is_reconstruction, 

764 possible_sense or sense, 

765 ) 

766 elif is_list(node) or kind in ( 

767 NodeKind.TABLE, 

768 NodeKind.TABLE_ROW, 

769 NodeKind.TABLE_CELL, 

770 ): 

771 parse_linkage_recurse( 

772 wxr, 

773 node.children, 

774 field, 

775 possible_sense or sense, 

776 None, 

777 word, 

778 data, 

779 sense_datas, 

780 is_reconstruction, 

781 ) 

782 elif kind in ( 782 ↛ 786line 782 didn't jump to line 786 because the condition on line 782 was never true

783 NodeKind.TABLE_HEADER_CELL, 

784 NodeKind.TABLE_CAPTION, 

785 ): 

786 continue 

787 elif kind == NodeKind.HTML: 787 ↛ 788line 787 didn't jump to line 788 because the condition on line 787 was never true

788 classes = (node.attrs.get("class") or "").split() 

789 if node.sarg in ("gallery", "ref", "cite", "caption"): 

790 continue 

791 elif node.sarg == "ruby": 

792 rb = parse_ruby(wxr, node) 

793 if rb: 

794 ruby.append(rb) 

795 parts.append(rb[0]) 

796 continue 

797 elif node.sarg == "math": 

798 parts.append(clean_node(wxr, None, node)) 

799 continue 

800 elif "interProject" in classes: 

801 continue # These do not seem to be displayed 

802 if "NavFrame" in classes: 

803 parse_linkage_recurse( 

804 wxr, 

805 node.children, 

806 field, 

807 possible_sense or sense, 

808 None, 

809 word, 

810 data, 

811 sense_datas, 

812 is_reconstruction, 

813 ) 

814 else: 

815 item_recurse(node.children, possible_sense) 

816 elif kind == NodeKind.LINK: 

817 ignore = False 

818 if isinstance(node.largs[0][0], str): 818 ↛ 706line 818 didn't jump to line 706 because the condition on line 818 was always true

819 v1 = node.largs[0][0].strip().lower() 

820 if v1.startswith( 820 ↛ 824line 820 didn't jump to line 824 because the condition on line 820 was never true

821 ns_title_prefix_tuple(wxr, "Category", True) 

822 + ns_title_prefix_tuple(wxr, "File", True) 

823 ): 

824 ignore = True 

825 if not ignore: 825 ↛ 706line 825 didn't jump to line 706 because the condition on line 825 was always true

826 v = node.largs[-1] 

827 if ( 

828 len(node.largs) == 1 

829 and len(v) > 0 

830 and isinstance(v[0], str) 

831 and v[0][0] == ":" 

832 ): 

833 v = [v[0][1:]] + list(v[1:]) # type:ignore 

834 if ( 

835 len(v) > 0 

836 and isinstance(v[0], str) 

837 and not v[0].isalnum() 

838 ): 

839 links_that_should_not_be_split.append("".join(v[0])) # type: ignore 

840 item_recurse(v, possible_sense) 

841 elif kind == NodeKind.URL: 

842 if len(node.largs) < 2 and node.largs: 

843 # Naked url captured 

844 urls.extend(node.largs[-1]) # type:ignore[arg-type] 

845 continue 

846 if len(node.largs) == 2: 846 ↛ 851line 846 didn't jump to line 851 because the condition on line 846 was always true

847 # Url from link with text 

848 urls.append(node.largs[0][-1]) # type:ignore[arg-type] 

849 # print(f"{node.largs=!r}") 

850 # print("linkage recurse URL {}".format(node)) 

851 item_recurse(node.largs[-1], possible_sense) 

852 elif kind in ( 852 ↛ 859line 852 didn't jump to line 859 because the condition on line 852 was always true

853 NodeKind.PREFORMATTED, 

854 NodeKind.BOLD, 

855 NodeKind.ITALIC, 

856 ): 

857 item_recurse(node.children) 

858 else: 

859 wxr.wtp.debug( 

860 "linkage item_recurse unhandled {}: {}".format( 

861 node.kind, node 

862 ), 

863 sortid="page/2073", 

864 ) 

865 

866 return is_sense 

867 

868 # print("LINKAGE CONTENTS BEFORE ITEM_RECURSE: {!r}" 

869 # .format(contents)) 

870 

871 is_sense = item_recurse(contents) 

872 

873 if not is_sense: 

874 item = clean_node(wxr, None, parts) 

875 # print("LINKAGE ITEM CONTENTS:", parts) 

876 # print("CLEANED ITEM: {!r}".format(item)) 

877 # print(f"URLS {urls=!r}") 

878 

879 if v := parse_linkage_item_text( 879 ↛ 892line 879 didn't jump to line 892 because the condition on line 879 was never true

880 wxr, 

881 word, 

882 data, 

883 field, 

884 item, 

885 sense, 

886 ruby, 

887 sense_datas, 

888 is_reconstruction, 

889 urls or None, 

890 links_that_should_not_be_split or None, 

891 ): 

892 return [v] 

893 

894 return [] 

895 

896 

897def parse_linkage_item_text( 

898 wxr: WiktextractContext, 

899 word: str, 

900 data: WordData, 

901 field: str, 

902 item: str, 

903 sense: Optional[str], 

904 ruby: list, 

905 pos_datas: list, 

906 is_reconstruction: bool, 

907 urls: Optional[list[str]] = None, 

908 links: Optional[list[str]] = None, 

909) -> Optional[str]: 

910 """Parses a linkage item once it has been converted to a string. This 

911 may add one or more linkages to ``data`` under ``field``. This 

912 returns None or a string that contains a sense that should be applied 

913 to additional linkages (commonly used in tables for Asian characters).""" 

914 assert isinstance(wxr, WiktextractContext) 

915 assert isinstance(word, str) # Main word (derived from page title) 

916 assert isinstance(data, dict) # Parsed linkages are stored here under field 

917 assert isinstance(field, str) # The field under which to store linkage 

918 assert isinstance(item, str) # The string to parse 

919 assert sense is None or isinstance(sense, str) 

920 assert isinstance(ruby, list) # Captured ruby (hiragana/katakana) or "" 

921 assert isinstance(pos_datas, list) # List of senses (containing "glosses") 

922 assert urls is None or isinstance(urls, list) # Captured urls 

923 assert is_reconstruction in (True, False) 

924 

925 item = item.replace("()", "") 

926 item = re.sub(r"\s+", " ", item) 

927 item = item.strip() 

928 

929 base_roman = None 

930 base_alt = None 

931 base_english = None 

932 script_chars = False 

933 base_qualifier = None 

934 lang = wxr.wtp.section 

935 

936 # If ``sense`` can be parsed as tags, treat it as tags instead 

937 if sense: 

938 cls = classify_desc(sense, no_unknown_starts=True) 

939 if cls == "tags": 

940 base_qualifier = sense 

941 sense = None 

942 

943 # Check if this item is a stand-alone sense (or tag) specifier 

944 # for following items (e.g., commonly in a table, see 滿) 

945 m = re.match(r"\(([-a-zA-Z0-9 ]+)\):$", item) 

946 if m: 

947 return m.group(1) 

948 

949 # Check for pre-split ignored linkages using the appropriate regexp 

950 if re.search(linkage_pre_split_ignore_re, item): 

951 return None 

952 

953 # print(" LINKAGE ITEM: {}: {} (sense {})" 

954 # .format(field, item, sense)) 

955 

956 # Replace occurrences of ~ in the item by the page title 

957 safetitle = wxr.wtp.title.replace("\\", "\\\\") # type: ignore[union-attr] 

958 item = item.replace(" ~ ", " " + safetitle + " ") 

959 item = re.sub(r"^~ ", safetitle + " ", item) 

960 item = re.sub(r" ~$", " " + safetitle, item) 

961 

962 # Many taxonomic terms contain hyponym lists that end with the 

963 # kind of the hyponym (a taxonomic level in plural). Recognize 

964 # such and add the term in singular to all linkages in the list. 

965 m = re.search(taxonomic_ending_re, item) 

966 if m: 

967 base_english = taxonomic_ending_map[m.group(1)] 

968 item = item[: m.start()] 

969 

970 # Some Korean and Japanese words use "word (romanized): english" pattern 

971 # Sometimes the parenthesized part contains comma-separated alt and roman. 

972 m = re.match(r"(.+?) \(([^():]+)\): ([-a-zA-Z0-9,. ]+)$", item) 

973 if m: 

974 rom = m.group(2) 

975 eng = m.group(3) 

976 rest = m.group(1) 

977 if ( 

978 classify_desc(rest, no_unknown_starts=True) == "other" 

979 and classify_desc(eng, no_unknown_starts=True) == "english" 

980 ): 

981 item = rest 

982 base_roman = rom 

983 lst = base_roman.split(", ") 

984 if ( 

985 len(lst) == 2 

986 and classify_desc(lst[0], no_unknown_starts=True) == "other" 

987 ): 

988 base_alt = lst[0] 

989 base_roman = lst[1] 

990 if base_english: 

991 base_english += "; " + eng 

992 else: 

993 base_english = eng 

994 

995 # Many words have tags or similar descriptions in the beginning 

996 # followed by a colon and one or more linkages (e.g., 

997 # panetella/Finnish) 

998 m = re.match(r"^\((([^():]|\([^()]*\))+)\): ([^:]*)$", item) or re.match( 

999 r"^([a-zA-Z][-'a-zA-Z0-9 ]*" r"(\([^()]+\)[-'a-zA-Z0-9 ]*)*): ([^:]*)$", 

1000 item, 

1001 ) 

1002 if m: 

1003 desc = m.group(1) 

1004 rest = m.group(len(m.groups())) 

1005 # Check for certain comma-separated tags combined 

1006 # with English text at the beginning or end of a 

1007 # comma-separated parenthesized list 

1008 lst = split_at_comma_semi(desc, skipped=links) 

1009 while len(lst) > 1: 

1010 # Check for tags at the beginning 

1011 cls = classify_desc(lst[0], no_unknown_starts=True) 

1012 if cls == "tags": 

1013 if base_qualifier: 

1014 base_qualifier += ", " + lst[0] 

1015 else: 

1016 base_qualifier = lst[0] 

1017 lst = lst[1:] 

1018 continue 

1019 # Check for tags at the end 

1020 cls = classify_desc(lst[-1], no_unknown_starts=True) 

1021 if cls == "tags": 

1022 if base_qualifier: 

1023 base_qualifier += ", " + lst[-1] 

1024 else: 

1025 base_qualifier = lst[-1] 

1026 lst = lst[:-1] 

1027 continue 

1028 break 

1029 desc = ", ".join(lst) 

1030 

1031 # Sometimes we have e.g. "chemistry (slang)" with are 

1032 # both tags (see "stink"). Handle that case by 

1033 # removing parentheses if the value is still tags. The part with 

1034 # parentheses could be on either side of the colon. 

1035 if "(" in desc: 

1036 x = desc.replace("(", ",").replace(")", ",") 

1037 if classify_desc(x, no_unknown_starts=True) == "tags": 

1038 desc = x 

1039 elif "(" in rest: 

1040 x = rest.replace("(", ",").replace(")", ",") 

1041 if classify_desc(x, no_unknown_starts=True) == "tags": 

1042 rest = desc 

1043 desc = x 

1044 

1045 # See if the prefix should trigger special handling for script 

1046 # character, letter, digit, etc. handling 

1047 if re.search(script_chars_re, desc): 

1048 script_chars = True 

1049 

1050 # Try to determine which side is description and which is 

1051 # the linked term (both orders are widely used in Wiktionary) 

1052 cls = classify_desc(desc, no_unknown_starts=True) 

1053 cls2 = classify_desc(rest, no_unknown_starts=True) 

1054 # print("linkage prefix: desc={!r} cls={} rest={!r} cls2={}" 

1055 # .format(desc, cls, rest, cls2)) 

1056 

1057 e1 = wxr.wtp.page_exists(desc) 

1058 e2 = wxr.wtp.page_exists(rest) 

1059 if cls != "tags": 

1060 if ( 

1061 cls2 == "tags" 

1062 or (e1 and not e1) 

1063 or ( 

1064 e1 

1065 and e2 

1066 and cls2 == "english" 

1067 and cls in ("other", "romanization") 

1068 ) 

1069 or ( 

1070 not e1 

1071 and not e2 

1072 and cls2 == "english" 

1073 and cls in ("other", "romanization") 

1074 ) 

1075 ): 

1076 desc, rest = rest, desc # Looks like swapped syntax 

1077 cls = cls2 

1078 if re.search(linkage_paren_ignore_contains_re, desc): 1078 ↛ 1079line 1078 didn't jump to line 1079 because the condition on line 1078 was never true

1079 desc = "" 

1080 # print("linkage colon prefix desc={!r} rest={!r} cls={}" 

1081 # .format(desc, rest, cls)) 

1082 

1083 # Handle the prefix according to its type 

1084 if cls == "tags": 

1085 if base_qualifier: 

1086 base_qualifier += ", " + desc 

1087 else: 

1088 base_qualifier = desc 

1089 item = rest 

1090 elif desc in ("NATO phonetic", "Morse code", "Braille", "ASL Manual"): 

1091 if base_english: 1091 ↛ 1092line 1091 didn't jump to line 1092 because the condition on line 1091 was never true

1092 base_english += "; " + base_english 

1093 else: 

1094 base_english = desc 

1095 item = rest 

1096 elif cls in ("english", "taxonomic"): 

1097 if sense: 1097 ↛ 1098line 1097 didn't jump to line 1098 because the condition on line 1097 was never true

1098 sense += "; " + desc 

1099 else: 

1100 sense = desc 

1101 item = rest 

1102 elif desc.isdecimal(): 

1103 idx = int(desc) - 1 

1104 if idx >= 0 and idx < len(pos_datas): 

1105 d = pos_datas[idx] 

1106 gl = "; ".join(d.get("glosses", ())) 

1107 if not gl: 1107 ↛ 1108line 1107 didn't jump to line 1108 because the condition on line 1107 was never true

1108 wxr.wtp.debug( 

1109 "parenthesized numeric linkage prefix, " 

1110 "but the referenced sense has no gloss: " 

1111 "{}".format(desc), 

1112 sortid="linkages/355", 

1113 ) 

1114 elif sense: 

1115 sense += "; " + gl 

1116 else: 

1117 sense = gl 

1118 item = rest 

1119 else: 

1120 wxr.wtp.debug( 

1121 "parenthesized numeric linkage prefix, " 

1122 "but there is no sense with such index: {}".format(desc), 

1123 sortid="linkages/365", 

1124 ) 

1125 item = rest 

1126 else: 

1127 wxr.wtp.debug( 

1128 "unrecognized linkage prefix: {} desc={} rest={} " 

1129 "cls={} cls2={} e1={} e2={}".format( 

1130 item, desc, rest, cls, cls2, e1, e2 

1131 ), 

1132 sortid="linkages/371", 

1133 ) 

1134 item = rest 

1135 

1136 base_sense = sense 

1137 

1138 # Check for certain plural tag forms at end of items list, and apply 

1139 # them to all items if found 

1140 m = re.search( 

1141 r" [-‐‑‒–—―] (diminutives|Diminutives|letters|digits|" 

1142 r"characters|symbols|tetragrams|letter names|names|" 

1143 r"female names|male names|proper nouns|contractions|" 

1144 r"nonstandard spellings|verbs|prepositions|postpositions|" 

1145 r"interjections|Abbreviations|abbreviations|variants|" 

1146 r"ordinals|nouns|phrases|adjectives|adverbs|" 

1147 r"augmentatives|pejoratives|compound words|numerals|" 

1148 r"Tally marks|surnames|modern nonstandard spellings)$", 

1149 item, 

1150 ) 

1151 if m: 

1152 suffix = m.group(1) 

1153 if base_qualifier: 

1154 base_qualifier += ", " + suffix 

1155 else: 

1156 base_qualifier = suffix 

1157 item = item[: m.start()] 

1158 

1159 # Certain linkage items have space-separated valus. These are 

1160 # generated by, e.g., certain templates 

1161 if base_sense and base_sense.endswith(" paper sizes"): 

1162 base_qualifier = None 

1163 item = ", ".join(item.split()) 

1164 # XXX isn't this now handled by the generic digits/letters/etc code? 

1165 # elif base_qualifier in ("Arabic digits",): 

1166 # item = ", ".join(item.split()) 

1167 

1168 item = re.sub(r"\s*\^\(\s*\)|\s*\^\s+", "", item) # Now empty superscript 

1169 item = item.strip() 

1170 if not item: 

1171 return None 

1172 

1173 # Kludge: if the item contains ")/" (with possibly spaces in between), 

1174 # replace it by a comma so it gets split. 

1175 item = re.sub(r"\)\s*/", "), ", item) 

1176 

1177 # The item may contain multiple comma-separated linkages 

1178 if base_roman: 

1179 subitems = [item] 

1180 else: 

1181 # Split at commas. Also, in most cases split by " or ", but this 

1182 # is complicated - "or" may end certain words (e.g., "logical or") 

1183 # and it may separate head-final tags (e.g. "foo f or m"). Also, 

1184 # some words have parenthesizxed parts in between, e.g., 

1185 # wife/English/Translations/Yiddish: 

1186 # "ווײַב‎ n (vayb) or f, פֿרוי‎ f (froy)" 

1187 subitems = [] 

1188 for item1 in split_at_comma_semi(item, skipped=links): 

1189 if " or " not in item1: 

1190 subitems.append(item1) 

1191 continue 

1192 # Item1 contains " or " 

1193 item2 = re.sub(r"\s*\([^)]*\)", "", item1) 

1194 item2 = re.sub(r"\s+", " ", item2) 

1195 if ( 

1196 ( 

1197 lang not in head_final_bantu_langs 

1198 or not re.search(head_final_bantu_re, item2) 

1199 ) 

1200 and ( 

1201 lang not in head_final_other_langs 

1202 or not re.search(head_final_other_re, item2) 

1203 ) 

1204 and ( 

1205 not re.search(head_final_re, item2) 

1206 or ( 

1207 item2[-1].isdecimal() 

1208 and lang not in head_final_numeric_langs 

1209 ) 

1210 ) 

1211 and not re.search(r"\bor\b", wxr.wtp.title or "MISSING_TITLE") 

1212 and all( 

1213 wxr.wtp.title not in x.split(" or ") 

1214 for x in split_at_comma_semi(item2, skipped=links) 

1215 if " or " in x 

1216 ) 

1217 ): 

1218 # We can split this item. Split the non-cleaned version 

1219 # that still has any intervening parenthesized parts. 

1220 subitems.extend( 

1221 split_at_comma_semi(item1, extra=[" or "], skipped=links) 

1222 ) 

1223 else: 

1224 subitems.append(item1) 

1225 if len(subitems) > 1: # Would be merged from multiple subitems 

1226 ruby = [] # XXX what is the purpose of this? 

1227 for item1 in subitems: 

1228 if len(subitems) > 1 and item1 in ("...", "…"): 

1229 # Some lists have ellipsis in the middle - don't generate 

1230 # linkages for the ellipsis 

1231 continue 

1232 item1 = item1.strip() 

1233 qualifier = base_qualifier 

1234 sense = base_sense 

1235 parts = [] 

1236 roman = base_roman # Usually None 

1237 alt = base_alt # Usually None 

1238 taxonomic = None 

1239 english = base_english 

1240 

1241 # Some words have derived terms with parenthesized quoted English 

1242 # descriptions, which can sometimes essentially be tags 

1243 # Some word (bleki/Esperanto...) can have parentheses inside 

1244 # the quotes, so let's make this regex even more unreadable. 

1245 m = re.search(r"\s*\(“([^”]+)”\)", item1) 

1246 if m: 1246 ↛ 1247line 1246 didn't jump to line 1247 because the condition on line 1246 was never true

1247 t = m.group(1) 

1248 item1 = (item1[: m.start()] + item1[m.end() :]).strip() 

1249 cls = classify_desc(t) 

1250 if cls == "tags": 

1251 if qualifier: 

1252 qualifier += ", " + t 

1253 else: 

1254 qualifier = t 

1255 else: 

1256 english = t 

1257 

1258 # Some Korean words use "word (alt, oman, “english”) pattern 

1259 # See 滿/Korean 

1260 m = re.match( 

1261 r"([^(),;:]+) \(([^(),;:]+), ([^(),;:]+), " 

1262 r'[“”"]([^”“"]+)[“”"]\)$', 

1263 item1, 

1264 ) 

1265 if ( 

1266 m 

1267 and classify_desc(m.group(1), no_unknown_starts=True) == "other" 

1268 and classify_desc(m.group(2), no_unknown_starts=True) == "other" 

1269 ): 

1270 alt = m.group(2) 

1271 roman = m.group(3) 

1272 english = m.group(4) 

1273 item1 = m.group(1) 

1274 

1275 words = item1.split(" ") 

1276 if ( 

1277 len(words) > 1 

1278 and words[0] in linkage_beginning_tags 

1279 and words[0] != wxr.wtp.title 

1280 ): 

1281 t = linkage_beginning_tags[words[0]] 

1282 item1 = " ".join(words[1:]) 

1283 if qualifier: 1283 ↛ 1284line 1283 didn't jump to line 1284 because the condition on line 1283 was never true

1284 qualifier += ", " + t 

1285 else: 

1286 qualifier = t 

1287 

1288 # Extract quoted English translations (there are also other 

1289 # kinds of English translations) 

1290 def english_repl(m: re.Match) -> str: 

1291 nonlocal english 

1292 nonlocal qualifier 

1293 v = m.group(1).strip() 

1294 # If v is "tags: sense", handle the tags 

1295 m1 = re.match(r"^([a-zA-Z ]+): (.*)$", v) 

1296 if m1 is not None: 1296 ↛ 1297line 1296 didn't jump to line 1297 because the condition on line 1296 was never true

1297 desc, rest = m1.groups() 

1298 if classify_desc(desc, no_unknown_starts=True) == "tags": 

1299 if qualifier: 

1300 qualifier += ", " + desc 

1301 else: 

1302 qualifier = desc 

1303 v = rest 

1304 if english: 

1305 english += "; " + v 

1306 else: 

1307 english = v 

1308 return "" 

1309 

1310 item1 = re.sub(r'[“"]([^“”"]+)[“”"],?\s*', english_repl, item1).strip() 

1311 

1312 # There could be multiple parenthesized parts, and 

1313 # sometimes both at the beginning and at the end. 

1314 # And sometimes even in the middle, as in e.g. 

1315 # wife/English/Translations/Yiddish 

1316 while not script_chars and ( 

1317 not sense or not re.search(script_chars_re, sense) 

1318 ): 

1319 par = None 

1320 nonfirst_par = False 

1321 if par is None: 1321 ↛ 1338line 1321 didn't jump to line 1338 because the condition on line 1321 was always true

1322 # Try to find a parenthesized part from the beginning. 

1323 m = re.match(r"\((([^()]|\([^()]*\))*)\):?\s*", item1) 

1324 if m: 

1325 par = m.group(1) 

1326 item1 = item1[m.end() :] 

1327 else: 

1328 # Try to find a parenthesized part at the end or from the 

1329 # middle. 

1330 m = re.search( 

1331 r"\s+\((\d|\d\d|[^\d]([^()]|\([^()]*\))*)\)" r"(\.$)?", 

1332 item1, 

1333 ) 

1334 if m: 

1335 par = m.group(1) 

1336 item1 = item1[: m.start()] + item1[m.end() :] 

1337 nonfirst_par = True 

1338 if not par: 

1339 break 

1340 if re.search(linkage_paren_ignore_contains_re, par): 

1341 continue # Skip these linkage descriptors 

1342 par = par.strip() 

1343 # Handle tags from beginning of par. We also handle "other" 

1344 # here as Korean entries often have Hanja form in the 

1345 # beginning of parenthesis, before romanization. Similar 

1346 # for many Japanese entries. 

1347 while par: 1347 ↛ 1368line 1347 didn't jump to line 1368 because the condition on line 1347 was always true

1348 idx = par.find(",") 

1349 if idx <= 0: 

1350 break 

1351 cls = classify_desc(par[:idx], no_unknown_starts=True) 

1352 if cls == "other" and not alt: 1352 ↛ 1353line 1352 didn't jump to line 1353 because the condition on line 1352 was never true

1353 alt = par[:idx] 

1354 elif cls == "taxonomic": 1354 ↛ 1355line 1354 didn't jump to line 1355 because the condition on line 1354 was never true

1355 taxonomic = par[:idx] 

1356 elif cls == "tags": 

1357 if qualifier: 

1358 qualifier += ", " + par[:idx] 

1359 else: 

1360 qualifier = par[:idx] 

1361 else: 

1362 break 

1363 par = par[idx + 1 :].strip() 

1364 

1365 # Check for certain comma-separated tags combined 

1366 # with English text at the beginning or end of a 

1367 # comma-separated parenthesized list 

1368 lst = par.split(",") if len(par) > 1 else [par] 

1369 lst = list(x.strip() for x in lst if x.strip()) 

1370 while len(lst) > 1: 

1371 cls = classify_desc(lst[0], no_unknown_starts=True) 

1372 if cls == "tags": 1372 ↛ 1373line 1372 didn't jump to line 1373 because the condition on line 1372 was never true

1373 if qualifier: 

1374 qualifier += ", " + lst[0] 

1375 else: 

1376 qualifier = lst[0] 

1377 lst = lst[1:] 

1378 continue 

1379 cls = classify_desc(lst[-1], no_unknown_starts=True) 

1380 if cls == "tags": 

1381 if qualifier: 

1382 qualifier += ", " + lst[-1] 

1383 else: 

1384 qualifier = lst[-1] 

1385 lst = lst[:-1] 

1386 continue 

1387 break 

1388 par = ", ".join(lst) 

1389 

1390 # Handle remaining types 

1391 if not par: 1391 ↛ 1392line 1391 didn't jump to line 1392 because the condition on line 1391 was never true

1392 continue 

1393 if re.search(script_chars_re, par): 

1394 script_chars = True 

1395 if classify_desc(par, no_unknown_starts=True) == "tags": 1395 ↛ 1405line 1395 didn't jump to line 1405 because the condition on line 1395 was always true

1396 if base_qualifier: 1396 ↛ 1397line 1396 didn't jump to line 1397 because the condition on line 1396 was never true

1397 base_qualifier += "; " + par 

1398 else: 

1399 base_qualifier = par 

1400 if qualifier: 1400 ↛ 1401line 1400 didn't jump to line 1401 because the condition on line 1400 was never true

1401 qualifier += "; " + par 

1402 else: 

1403 qualifier = par 

1404 else: 

1405 if base_sense: 

1406 base_sense += "; " + par 

1407 else: 

1408 base_sense = par 

1409 if sense: 

1410 sense += "; " + par 

1411 else: 

1412 sense = par 

1413 elif par.endswith(" letter names"): 1413 ↛ 1414line 1413 didn't jump to line 1414 because the condition on line 1413 was never true

1414 if base_qualifier: 

1415 base_qualifier += "; " + par 

1416 else: 

1417 base_qualifier = par 

1418 if qualifier: 

1419 qualifier += "; " + par 

1420 else: 

1421 qualifier = par 

1422 else: 

1423 cls = classify_desc(par) 

1424 # print("classify_desc: {!r} -> {}".format(par, cls)) 

1425 if cls == "tags": 

1426 if qualifier: 

1427 qualifier += ", " + par 

1428 else: 

1429 qualifier = par 

1430 elif cls == "english": 

1431 if nonfirst_par: 

1432 if english: 

1433 english += "; " + par 

1434 else: 

1435 english = par 

1436 else: 

1437 if sense: 1437 ↛ 1438line 1437 didn't jump to line 1438 because the condition on line 1437 was never true

1438 sense += "; " + par 

1439 else: 

1440 sense = par 

1441 elif cls == "romanization": 

1442 roman = par 

1443 elif cls == "taxonomic": 

1444 taxonomic = par 

1445 elif par.isdecimal(): 

1446 idx = int(par) - 1 

1447 if idx >= 0 and idx < len(pos_datas): 

1448 d = pos_datas[idx] 

1449 gl = "; ".join(d.get("glosses", ())) 

1450 if not gl: 1450 ↛ 1451line 1450 didn't jump to line 1451 because the condition on line 1450 was never true

1451 wxr.wtp.debug( 

1452 "parenthesized number " 

1453 "but the referenced sense has no " 

1454 "gloss: {}".format(par), 

1455 sortid="linkages/665", 

1456 ) 

1457 elif sense: 1457 ↛ 1460line 1457 didn't jump to line 1460 because the condition on line 1457 was always true

1458 sense += "; " + gl 

1459 else: 

1460 sense = gl 

1461 else: 

1462 wxr.wtp.debug( 

1463 "parenthesized number but there is " 

1464 "no sense with such index: {}".format(par), 

1465 sortid="linkages/674", 

1466 ) 

1467 else: 

1468 if alt: 1468 ↛ 1469line 1468 didn't jump to line 1469 because the condition on line 1468 was never true

1469 alt += "; " + par 

1470 else: 

1471 alt = par 

1472 

1473 # Handle certain special cases, unless we are parsing 

1474 # script characters. 

1475 if not script_chars: 

1476 # Ignore all linkages with certain prefixes, suffixes, or parts 

1477 # (this is done after removing certain prefixes and suffixes) 

1478 if re.search(linkage_ignore_re, item1): 

1479 continue # Ignore linkages with certain prefixes 

1480 

1481 # Remove certain prefixes from linkages 

1482 m = re.match(linkage_remove_prefixes_re, item1) 

1483 if m: 

1484 prefix = item1[: m.end()] 

1485 item1 = item1[m.end() :] 

1486 if prefix in linkage_remove_prefixes_tags: 

1487 if qualifier: 

1488 qualifier += ", " + linkage_remove_prefixes_tags[prefix] 

1489 else: 

1490 qualifier = linkage_remove_prefixes_tags[prefix] 

1491 # Recheck ignored linkages 

1492 if re.search(linkage_ignore_re, item1): 

1493 continue 

1494 

1495 # Remove certain suffixes from linkages 

1496 m = re.search(linkage_remove_suffixes_re, item1) 

1497 if m: 

1498 item1 = item1[: m.start()] 

1499 

1500 # Parse linkages with "value = english" syntax (e.g., 

1501 # väittää/Finnish) 

1502 idx = item1.find(" = ") 

1503 if idx >= 0: 

1504 eng = item1[idx + 3 :] 

1505 if classify_desc(eng, no_unknown_starts=True) == "english": 

1506 english = eng 

1507 item1 = item1[:idx] 

1508 else: 

1509 # Some places seem to use it reversed 

1510 # "english = value" 

1511 eng = item1[:idx] 

1512 if classify_desc(eng, no_unknown_starts=True) == "english": 

1513 english = eng 

1514 item1 = item1[idx + 3 :] 

1515 

1516 # Parse linkages with "value - english" syntax (e.g., 

1517 # man/Faroese) 

1518 m = re.search(r" [-‐‑‒–—―] ", item1) 

1519 if m and "(" not in item1: 

1520 suffix = item1[m.end() :] 

1521 cls = classify_desc(suffix, no_unknown_starts=True) 

1522 if cls == "english": 

1523 # This case intentionally ignores old values from english 

1524 # (otherwise taxonomic lists fail) 

1525 english = suffix 

1526 item1 = item1[: m.start()] 

1527 elif cls == "tags": 

1528 if qualifier: 1528 ↛ 1529line 1528 didn't jump to line 1529 because the condition on line 1528 was never true

1529 qualifier += ", " + suffix 

1530 else: 

1531 qualifier = suffix 

1532 item1 = item1[: m.start()] 

1533 

1534 # Parse certain tags at the end of the linked term (unless 

1535 # we are in a letters list) 

1536 item1, q = parse_head_final_tags(wxr, lang or "MISSING_LANG", item1) 

1537 if q: 

1538 if qualifier: 1538 ↛ 1539line 1538 didn't jump to line 1539 because the condition on line 1538 was never true

1539 qualifier += ", " + ", ".join(q) 

1540 else: 

1541 qualifier = ", ".join(q) 

1542 

1543 m = re.search(linkage_truncate_re, item1) 

1544 if m: 1544 ↛ 1546line 1544 didn't jump to line 1546 because the condition on line 1544 was never true

1545 # suffix = item1[m.start():] # Currently ignored 

1546 item1 = item1[: m.start()] 

1547 if not item1: 

1548 continue # Ignore empty link targets 

1549 if item1 == word: 

1550 continue # Ignore self-links 

1551 

1552 def add(w: str, r: Optional[str]) -> None: 

1553 assert isinstance(w, str) 

1554 assert r is None or isinstance(r, str) 

1555 nonlocal alt 

1556 nonlocal taxonomic 

1557 

1558 # We remove "*" from the beginning of reconstruction linkages. 

1559 # Such linkages should only occur in reconstruction senses, so 

1560 # this should not cause ambiguity. 

1561 if is_reconstruction and w.startswith("*"): 

1562 w = w[1:] 

1563 

1564 # Check if the word contains the Fullwith Solidus, and if 

1565 # so, split by it and treat the the results as alternative 

1566 # linkages. (This is very commonly used for alternative 

1567 # written forms in Chinese compounds and other linkages.) 

1568 # However, if the word contains a comma, then we wont't 

1569 # split as this is used when we have a different number 

1570 # of romanizations than written forms, and don't know 

1571 # which is which. 

1572 if ( 

1573 (not w or "," not in w) 

1574 and (not r or "," not in r) 

1575 and not wxr.wtp.page_exists(w) 

1576 ): 

1577 lst = w.split("/") if len(w) > 1 else [w] 

1578 if len(lst) == 1: 

1579 lst = w.split(" / ") 

1580 if len(lst) == 1 and len(lst[0]) >= 6: 

1581 lst = w.split("/") 

1582 if len(lst) > 1: 

1583 # Treat each alternative as separate linkage 

1584 for w in lst: 

1585 add(w, r) 

1586 return None 

1587 

1588 # Heuristically remove "." at the end of most linkages 

1589 # (some linkage lists end in a period, but we also have 

1590 # abbreviations that end with a period that should be kept) 

1591 if ( 

1592 w.endswith(".") 

1593 and not wxr.wtp.page_exists(w) 

1594 and ( 

1595 wxr.wtp.page_exists(w[:-1]) 

1596 or (len(w) >= 5) 

1597 and "." not in w[:-1] 

1598 ) 

1599 ): 

1600 w = w[:-1] 

1601 

1602 # If we have roman but not alt and the word is ASCII, 

1603 # move roman to alt. 

1604 if r and not alt and w.isascii(): 

1605 alt = r 

1606 r = None 

1607 # Add the linkage 

1608 dt: LinkageData = {} 

1609 if qualifier: 

1610 parse_sense_qualifier(wxr, qualifier, dt) 

1611 if sense: 

1612 dt["sense"] = sense.strip() 

1613 if r: 

1614 dt["roman"] = r.strip() 

1615 if ruby: 

1616 dt["ruby"] = ruby 

1617 if english: 

1618 dt["english"] = english.strip() # DEPRECATED for "translation" 

1619 dt["translation"] = english.strip() 

1620 if taxonomic: 

1621 if re.match(r"×[A-Z]", taxonomic): 

1622 data_append(dt, "tags", "extinct") 

1623 taxonomic = taxonomic[1:] 

1624 dt["taxonomic"] = taxonomic 

1625 if re.match(r"×[A-Z]", w): 

1626 data_append(dt, "tags", "extinct") 

1627 w = w[1:] # Remove × before dead species names 

1628 if alt and re.match(r"×[A-Z]", alt): 

1629 data_append(dt, "tags", "extinct") 

1630 alt = alt[1:] # Remove × before dead species names 

1631 if alt and alt.strip() != w: 

1632 dt["alt"] = alt.strip() 

1633 if urls: 

1634 dt["urls"] = [ 

1635 url.strip() for url in urls if url and isinstance(url, str) 

1636 ] 

1637 dt["word"] = w 

1638 for old in data.get(field, ()): # type: ignore[attr-defined] 

1639 if dt == old: 

1640 break 

1641 else: 

1642 data_append(data, field, dt) 

1643 

1644 # Handle exceptional linkage splits and other linkage 

1645 # conversions (including expanding to variant forms) 

1646 if item1 in linkage_split_exceptions: 1646 ↛ 1647line 1646 didn't jump to line 1647 because the condition on line 1646 was never true

1647 for item2 in linkage_split_exceptions[item1]: 

1648 add(item2, roman) 

1649 continue 

1650 

1651 # Various templates for letters in scripts use spaces as 

1652 # separators and also have multiple characters without 

1653 # spaces consecutively. 

1654 v = sense or qualifier 

1655 # print("lang={} v={} script_chars={} item1={!r}" 

1656 # .format(wxr.wtp.section, v, script_chars, item1)) 

1657 if v and script_chars: 

1658 if ( 

1659 len(item1.split()) > 1 

1660 or len(list(re.finditer(unicode_dc_re, item1))) == 2 

1661 or (len(subitems) > 10 and v in ("Hiragana", "Katakana")) 

1662 ): 

1663 if v == qualifier: 

1664 # if sense: 

1665 # sense += "; " + qualifier 

1666 # else: 

1667 # sense = qualifier 

1668 qualifier = None 

1669 if re.search(r" (letters|digits|script)$", v): 

1670 qualifier = v # Also parse as qualifier 

1671 elif re.search( 1671 ↛ 1678line 1671 didn't jump to line 1678 because the condition on line 1671 was always true

1672 r"Variations of letter |" 

1673 r"Letters using |" 

1674 r"Letters of the ", 

1675 v, 

1676 ): 

1677 qualifier = "letter" 

1678 parts = item1.split(". ") 

1679 extra: Sequence[str] = () 

1680 if len(parts) > 1: 1680 ↛ 1681line 1680 didn't jump to line 1681 because the condition on line 1680 was never true

1681 extra = parts[1:] 

1682 item1 = parts[0] 

1683 # Handle multi-character names for chars in language's 

1684 # alphabet, e.g., "Ny ny" in P/Hungarian. 

1685 if ( 

1686 len(subitems) > 20 

1687 and len(item1.split()) == 2 

1688 and all(len(x) <= 3 for x in item1.split()) 

1689 ): 

1690 parts = list( 

1691 m.group(0) 

1692 for m in re.finditer(r"(\w[\u0300-\u036f]?)+|.", item1) 

1693 if not m.group(0).isspace() 

1694 and m.group(0) not in ("(", ")") 

1695 ) 

1696 else: 

1697 parts = list( 

1698 m.group(0) 

1699 for m in re.finditer(r".[\u0300-\u036f]?", item1) 

1700 if not m.group(0).isspace() 

1701 and m.group(0) not in ("(", ")") 

1702 ) 

1703 for e in extra: 1703 ↛ 1704line 1703 didn't jump to line 1704 because the loop on line 1703 never started

1704 idx = e.find(":") 

1705 if idx >= 0: 

1706 e = e[idx + 1 :].strip() 

1707 if e.endswith("."): 

1708 e = e[:-1] 

1709 parts.extend(e.split()) 

1710 

1711 # XXX this is not correct - see P/Vietnamese 

1712 # While some sequences have multiple consecutive 

1713 # characters, others use pairs and some have 

1714 # 2/3 character names, e.g., "Ng ng". 

1715 

1716 rparts: Optional[list[Optional[str]]] = None 

1717 if roman: 1717 ↛ 1718line 1717 didn't jump to line 1718 because the condition on line 1717 was never true

1718 rparts = list( 

1719 m.group(0) 

1720 for m in re.finditer(r".[\u0300-\u036f]", roman) 

1721 if not m.group(0).isspace() 

1722 ) 

1723 if len(rparts) != len(parts): 

1724 rparts = None 

1725 if not rparts: 1725 ↛ 1728line 1725 didn't jump to line 1728 because the condition on line 1725 was always true

1726 rparts = [None] * len(parts) 

1727 

1728 for w, r in zip(parts, rparts): 

1729 add(w, r) 

1730 continue 

1731 

1732 add(item1, roman) 

1733 return None