From 94a8d2a5ba84e765d5118cea5f99069373a7a324 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Mon, 16 Nov 2026 00:19:27 -0800 Subject: [PATCH 1/2] Simplify _comma.py, _pieces.py and _vocab.py The 3.1 release's simplify pass over three modules this cycle changed. Readings unchanged: snapshot.jsonl byte-identical, every agreement view matches its record. - _vocab: T8's unambiguous title-or-suffix test after a glued stop, written twice (glued_cuts, glued_saint_cut), is one helper - _vocab: one joiner constant for O9's capitals word and the Cyrillic order key, which held the same six characters under two names - _vocab: is_initial_chunk asks _is_cased_letter; is_capitals_word drops a counter its chunk count implies and a dead while-else - _vocab: glued_cuts and glued_saint_cut ask their C-level matches before the fold's frame - _comma: one helper builds the credential fork C13 and C16 report; C16's one-element run set is an index; C13 keeps the whole-name answer it computes; C6's contrast fills the box its helpers read - comments trimmed to the citation form, history left in decisions/; _comma's Reads: line names the sets it reads directly Co-Authored-By: Claude Opus 5.5 --- nameparser/_pipeline/_comma.py | 72 +++++++++++++--------- nameparser/_pipeline/_pieces.py | 24 ++------ nameparser/_pipeline/_vocab.py | 106 ++++++++++++++++---------------- tests/v2/test_layering.py | 6 +- 4 files changed, 105 insertions(+), 103 deletions(-) diff --git a/nameparser/_pipeline/_comma.py b/nameparser/_pipeline/_comma.py index 531d69956..017bf2b60 100644 --- a/nameparser/_pipeline/_comma.py +++ b/nameparser/_pipeline/_comma.py @@ -22,6 +22,9 @@ _vocab.caps_shape_candidate (to know an all-caps word is unlisted) and _vocab.claimed_as_non_name (the name's contrast); Lexicon .maiden_markers through _pieces.own_words, for the name's contrast; +Lexicon.generation_words, Lexicon.suffix_words_ambiguous and +Lexicon.suffix_acronyms_ambiguous, for a chunk of a joined word beside +a pair of capitals (rules/C5); Lexicon.capitalization_exceptions, a credential's case mask, for rules/C13's given-name Except; Policy.lenient_comma_suffixes, Policy.extra_suffix_delimiters, Policy.unlisted_caps_suffixes and Policy.unlisted_dotted_suffixes. @@ -558,12 +561,18 @@ def _run_read_as_initials(state: ParseState, i: int) -> ParseState: token = tokens[i] tokens[i] = copy_with(token, tags=token.tags | {"initial"}) return copy_with(state, tokens=tuple(tokens), ambiguities=( - *state.ambiguities, - PendingAmbiguity( - AmbiguityKind.SUFFIX_OR_NAME, - f"{token.text!r} after the comma also spells a credential; " - f"read as ", (i,), field_tail="", - alternative=suffix_reading(token)))) + *state.ambiguities, _credential_fork(token, i))) + + +def _credential_fork(token: WorkToken, i: int) -> PendingAmbiguity: + """The report of the word at `i` after the comma read as a name + where the other branch is the credential it spells (rules/C13, + rules/C16).""" + return PendingAmbiguity( + AmbiguityKind.SUFFIX_OR_NAME, + f"{token.text!r} after the comma also spells a credential; " + f"read as ", (i,), field_tail="", + alternative=suffix_reading(token)) def _given_name_written_short(part: Sequence[int], @@ -588,7 +597,7 @@ def _given_name_written_short(part: Sequence[int], if k + 1 == len(part): # alone: a title in front leaves the given part's walk nothing # but the title to read as the name, so the part stays the - # postnominal one there (#1395's second review) + # postnominal one there (decisions/C13 (#1395)) if k or one_case or not any(map(str.islower, token.text)): return None bare = token.text.replace(".", "") @@ -680,16 +689,15 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: # it is taken, as a word of the ambiguous class reports it (C4) for i in part: if GIVEN_ABBREVIATION_TAG in tokens[i].tags: - at = _given_name_written_short(part, tokens, state.one_case, lex) - if at is not None and not _whole_name(seg0, tokens, state.one_case): - token = tokens[at] - return copy_with(state, ambiguities=( - *state.ambiguities, - PendingAmbiguity( - AmbiguityKind.SUFFIX_OR_NAME, - f"{token.text!r} after the comma also spells a " - f"credential; read as ", (at,), field_tail="", - alternative=suffix_reading(token)))) + short = _given_name_written_short(part, tokens, state.one_case, + lex) + if short is not None: + if whole is None: + whole = _whole_name(seg0, tokens, state.one_case) + if not whole: + return copy_with(state, ambiguities=( + *state.ambiguities, + _credential_fork(tokens[short], short))) break if pol.unlisted_dotted_suffixes: # rules/S3: "Paired initials are the exception [...] where S4 @@ -758,8 +766,7 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: # where the part holds a full stop, so 'Smith, John' pays no frame; # a part whose other words are all credentials is C8's run # ('Smith, M.D. Ph.D.'). - runs: set[int] = set() - at = -1 + initials_at: int | None = None for at, p in enumerate(p1): if len(p) == 1 and "." in (text := texts[p[0]]): tags = tokens[p[0]].tags @@ -777,11 +784,10 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: # the first run is the one asked about; another run # beside it is company like any credential ('Anderson, # M.T. B.A.') - runs.add(p[0]) + initials_at = p[0] break contrast_box: list[bool] = [] - if runs: - first = p1[at][0] + if initials_at is not None: # titles in front of the run are the given part's (C16); # behind it a credential is company: a title/suffix dual only in # capitals ('Smith, M.D. MS', but 'Smith, J.P. Ms.'), never a @@ -793,9 +799,9 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: and not (len(p) == 1 and texts[p[0]] in cores)] if rest and all(_company(state, seg0, p, pt, texts, contrast_box) for p, pt in rest): - runs.clear() - elif first not in maybe: - maybe.append(first) + initials_at = None + elif initials_at not in maybe: + maybe.append(initials_at) # rules/C8: "a part that is nothing but suffix words is the # credential run and reads as suffixes, whole" -- the reading below. # The part is read ONCE: here where it holds no word of the class, @@ -864,6 +870,8 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: and caps_shape_candidate(text, lex, pol, one_case=False)): if contrast is None: contrast = _name_contrast(state, seg0) + # the box the helpers below read, empty until now + contrast_box.append(contrast) # a two-capital word is how initials are written: the # paired-initials rule below discards one nothing speaks # for, a lone one included ('John Smith, XY') @@ -950,16 +958,20 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: and len(state.segments) > 2 and _listed_credentials_behind( state, seg0, cores, inner, contrast_box) - and _capitals_in_contrast(state, seg0, text, - contrast))): + and _capitals_in_contrast( + state, seg0, text, + contrast_box[0] if contrast_box + else contrast))): licensed.discard(i) caps.discard(i) if maybe: - lone = bool(runs) and names < 2 and _lone_word(state, seg0) + lone = (initials_at is not None and names < 2 + and _lone_word(state, seg0)) reading = segment_suffix_reading( p1, pt1, tokens, pol.lenient_comma_suffixes, state.one_case, anchored, absorbed, licensed, head_named=names >= 2, - runs=runs if lone else ()) + runs=(initials_at,) if lone and initials_at is not None + else ()) if reading is None and lone: # rules/C16: "behind one word, initials run together are the # given name whatever they spell" -- the run the reading @@ -970,7 +982,7 @@ def decide(state: ParseState, splits: bool | None = True) -> ParseState: # its unlisted twin 'Smith, X.Q.;' is k = next((j for j, p in enumerate(p1) if not is_title_piece(p, pt1[j], tokens)), -1) - if k >= 0 and p1[k][0] in runs: + if k >= 0 and p1[k][0] == initials_at: return _run_read_as_initials(state, p1[k][0]) if not listing: if whole is None: diff --git a/nameparser/_pipeline/_pieces.py b/nameparser/_pipeline/_pieces.py index ef4896f9a..02cf24fdd 100644 --- a/nameparser/_pipeline/_pieces.py +++ b/nameparser/_pipeline/_pieces.py @@ -494,26 +494,16 @@ def leading_titles(pieces: Sequence[Sequence[int]], # title 'Prince of Wales', family 'Jr', not given 'Prince of Wales' # with no title at all. # - # Two residuals. A run whose last word IS suffix vocabulary is not - # given back, so 'Dr Pope RA PhD' still reads title 'Dr Pope RA', - # family 'PhD'. And the floor asks is_suffix_piece, which vetoes a - # bare initial-shaped numeral, so 'Dr Pope V' keeps the whole run - # as the title and reads the numeral as the name -- given 'V', - # 'pope' being a given-name title and the run's last word, where - # 'Dr Smith V' reads family 'V' (a title being no word to spare - # for a one-letter numeral, #718). That numeral fork is outside - # this floor (decisions/H3). + # The residuals the floor does not reach (a run ending in suffix + # vocabulary, a bare numeral behind the run) are decisions/H3's. # # The two inline tag reads are the cheapest NECESSARY condition for # the piece behind the run to be a suffix piece at all -- # is_suffix_piece cannot answer yes without one of them -- so the # ordinary titled name, whose next piece is no kind of suffix, - # leaves this branch without entering a frame. Measured on the - # plan's ordering rather than the shape below: asking the - # authoritative predicate first cost 8 calls per parse of the - # reference name (leading_titles runs four times), against a band - # with room for two (decisions/parse-cost). is_suffix_piece - # stays the predicate that ANSWERS, here and in the walk. + # leaves this branch without entering a frame (decisions/H3, + # decisions/parse-cost). is_suffix_piece stays the predicate that + # ANSWERS, here and in the walk. if (n and n < len(pieces) and ("suffix" in ptags[n] or "vocab:suffix" in tokens[pieces[n][0]].tags) @@ -2449,9 +2439,7 @@ def _chain_units(pieces: Sequence[Sequence[int]], # word behind it inside the chain's run is one the chain # took because S8 starts no run there or declines one, so # the peel cannot reach it and it is no word of its own - # (rules/P2, #1177's - # review: 'Freiherr von Md Berg V' as 'Freiherr von Abdul - # Berg V') + # (rules/P2, decisions/P2 (#1177)) while (q < j and "split" not in ptags[q] and (not _weighed(pieces[q], tokens) or q + 1 < j diff --git a/nameparser/_pipeline/_vocab.py b/nameparser/_pipeline/_vocab.py index 556ea9d7f..0faa480f3 100644 --- a/nameparser/_pipeline/_vocab.py +++ b/nameparser/_pipeline/_vocab.py @@ -54,9 +54,9 @@ from collections.abc import Callable, Iterable, Sequence, Set from typing import Literal -from nameparser._lexicon import _HYPHEN_CHARS # rules/O6's hyphens, one definition from nameparser._lexicon import ( - FULL_STOPS, Lexicon, _VOCAB_FIELDS, _normalize, _spells_an_initial, + FULL_STOPS, Lexicon, _HYPHEN_CHARS, _VOCAB_FIELDS, _normalize, + _spells_an_initial, ) from nameparser._policy import ( CapsSuffixes, Policy, Script, _CASELESS_LETTERS, _EAST_ASIAN_SCRIPTS, @@ -125,15 +125,17 @@ _CYRILLIC_LETTERS = frozenset(chr(c) for lo, hi in _SCRIPT_RANGES[Script.CYRILLIC] for c in range(lo, hi + 1)) -#: The joiners a Cyrillic name word is written with inside it, hyphens -#: and the apostrophes Ukrainian and Belarusian write (`Оюун-Эрдэнэ`, -#: `Мар'яна`), deleted from the classified copy of a word that neither -#: opens nor ends with one, -#: so a hyphenated Cyrillic word keys a declared Cyrillic order as a -#: plain one does (#1237); the shared table stays letters only, since -#: the East Asian readers of it never see these. -_CYRILLIC_JOINERS = "-\u2010\u2011'\u2019\u02bc" -_DROP_CYRILLIC_JOINERS = str.maketrans("", "", _CYRILLIC_JOINERS) +#: The joiners a name word is written with inside it: hyphens and the +#: apostrophes a surname writes (`O'BRIEN`, `ALLIOT-MARIE`) and +#: Ukrainian and Belarusian write (`Оюун-Эрдэнэ`, `Мар'яна`). Read by +#: rules/O9's capitals word (`is_capitals_word`) and by the Cyrillic +#: order key, which deletes them from the classified copy of a word that +#: neither opens nor ends with one, so a hyphenated Cyrillic word keys a +#: declared Cyrillic order as a plain one does (#1237); the shared table +#: stays letters only, since the East Asian readers of it never see +#: these. +_NAME_JOINERS = "-\u2010\u2011'\u2019\u02bc" +_DROP_NAME_JOINERS = str.maketrans("", "", _NAME_JOINERS) # The whole-token matcher over _policy's _JA_SCRIPTS union, backing # effective_script's kana license. @@ -265,7 +267,8 @@ def in_unabbreviating_script(text: str) -> bool: _DIGRAPH_INITIALS = frozenset({"yu", "ya", "ye", "yo", "zh", "kh", "shch", "dzh"}) -#: The hyphens and the dashes that join two family names in one written +#: `_lexicon._HYPHEN_CHARS`, defined once there, matched as a class: +#: the hyphens and the dashes that join two family names in one written #: word (rules/O6), and the parts of an abbreviation written hyphenated #: (rules/H5, 'Dipl.‐Ing.' as a word processor writes it): hyphen-minus, #: hyphen, non-breaking hyphen, figure dash, en dash, minus sign (a word @@ -996,6 +999,18 @@ def _reads_alone(chunk: str, lexicon: Lexicon) -> bool: return is_title_chunk(chunk, lexicon) +def _claimed_after_the_stop(w: str, lexicon: Lexicon) -> bool: + """Whether the folded word W after a glued full stop is an + unambiguous title or suffix word, and so no name (rules/T8): the + one test `glued_cuts` and `glued_saint_cut` ask of it.""" + sets = lexicon._sets + return w in sets.titles or ( + w in sets.suffix_acronyms + and w not in sets.suffix_acronyms_ambiguous) or ( + (w in sets.suffix_words or w in sets.credential_words) + and w not in sets.suffix_words_ambiguous) + + def glued_cuts(text: str, lexicon: Lexicon) -> tuple[int, ...]: """Where a word glued to the next at a full stop divides (T8, #1230, #1235): the offset after each stop at which a chunk the @@ -1012,6 +1027,10 @@ def glued_cuts(text: str, lexicon: Lexicon) -> tuple[int, ...]: ('Dr.med', 'G.ppe'), at one closed by its own stop or followed by another chunk ('Dr.Med.', 'J.Smith.', 'Dr.John.Smith'), and at an unambiguous title or credential after the stop ('Dr.MD').""" + # a run of single letters alone is the walk's first answer below, + # `titled` being false there ('J.R.R.'), asked before the fold's frame + if _LETTER_RUN.fullmatch(text): + return () sets = lexicon._sets n = _normalize(text) bare = n.replace(".", "") @@ -1102,11 +1121,7 @@ def glued_cuts(text: str, lexicon: Lexicon) -> tuple[int, ...]: if len(tail) > 1 and not initial: return () w = _normalize(word.group()) - if w in sets.titles or ( - w in sets.suffix_acronyms - and w not in sets.suffix_acronyms_ambiguous) or ( - (w in sets.suffix_words or w in sets.credential_words) - and w not in sets.suffix_words_ambiguous): + if _claimed_after_the_stop(w, lexicon): return () cuts.append(end) at = end @@ -1168,23 +1183,22 @@ def glued_saint_cut(text: str, lexicon: Lexicon) -> int | None: (rules/T8, #1071). The word is one name word wherever it stands, and divides here only as the last word of a part (`_script_segment` asks that).""" + # the C-level matches first, which turn away nearly every word + # ('J.R.R.', 'Lt.Gov.'), before the fold's frame m = _GLUED_CHUNK.match(text) - if m is None or _normalize(m.group(1)) not in lexicon._sets.saint_particles: + if m is None: return None word = _GLUED_WORD.fullmatch(text, m.end()) - if word is None or next( - (c.islower() for c in word.group() if c.upper() != c.lower()), - True): + if (word is None + or _normalize(m.group(1)) not in lexicon._sets.saint_particles + or next( + (c.islower() for c in word.group() + if c.upper() != c.lower()), + True)): return None # an unambiguous title or suffix word after the stop is no name # ('St.MD', 'St.Jr') - sets = lexicon._sets - w = _normalize(word.group()) - if w in sets.titles or ( - w in sets.suffix_acronyms - and w not in sets.suffix_acronyms_ambiguous) or ( - (w in sets.suffix_words or w in sets.credential_words) - and w not in sets.suffix_words_ambiguous): + if _claimed_after_the_stop(_normalize(word.group()), lexicon): return None return m.end() @@ -1197,11 +1211,8 @@ def is_initial_chunk(chunk: str) -> bool: parts = chunk.split(".") if len(parts) == 1 and _normalize(chunk) in _DIGRAPH_INITIALS: return True - for part in parts: - part = unicodedata.normalize("NFC", part) - if len(part) != 1 or part.upper() == part.lower(): - return False - return True + return all(_is_cased_letter(unicodedata.normalize("NFC", part)) + for part in parts) def is_title_chunk(chunk: str, lexicon: Lexicon) -> bool: @@ -2134,20 +2145,13 @@ def in_any_wordlist(n: str, lexicon: Lexicon) -> bool: if f not in ("surnames", "bound_given_names")) -#: What a word written in capitals may hold besides its letters: the -#: apostrophes and hyphens a surname writes inside it (`O'BRIEN`, -#: `ALLIOT-MARIE`). Anything else -- a full stop, a slash, a digit, a -#: bracket or quotation mark -- says the word is no name written in -#: capitals (`DR.`, `N/A`, `GS.TS.`), rules/O9. -_CAPITALS_JOINERS = frozenset("'’ʼ-‐‑") - def is_capitals_word(text: str) -> bool: """Whether TEXT is a name written in capitals, as rules/O9 reads one: two or more letters in capitals ending the word, after any lowercase prefix glued in front (`DUPONT`, `O'BRIEN`, `McDONALD`, `d'ESTAING`), with nothing in it but letters, their combining marks - and `_CAPITALS_JOINERS`. Single letters joined by a hyphen are + and `_NAME_JOINERS`. Single letters joined by a hyphen are initials (`J-P`), and a word whose capitals are one letter is a name in mixed case (`PhD`, `McD`). A combining mark is passed over in the letter's run, so a capital typed as its base and an accent @@ -2157,35 +2161,31 @@ def is_capitals_word(text: str) -> bool: word = text # a joiner at either end is a quotation mark or a dash, not a name # written with one inside it ('MBA', -AB) - if not word or word[0] in _CAPITALS_JOINERS or word[-1] in _CAPITALS_JOINERS: + if not word or word[0] in _NAME_JOINERS or word[-1] in _NAME_JOINERS: return False - capitals = 0 chunk = longest = 0 i = len(word) while i: i -= 1 ch = word[i] if ch.isupper() or ch.islower() and len(ch.upper()) != 1: - capitals += 1 chunk += 1 continue if ch.islower(): break # the prefix glued in front: McDONALD, d'ESTAING - if ch in _CAPITALS_JOINERS: + if ch in _NAME_JOINERS: longest = max(longest, chunk) chunk = 0 continue if unicodedata.category(ch) in ("Mn", "Mc", "Me"): continue return False # a full stop, slash, digit, bracket or caseless letter - else: - i = -1 - if i >= 0 and not all(c.isalpha() or c in _CAPITALS_JOINERS + # i is 0 where no lowercase prefix stopped the walk + if i and not all(c.isalpha() or c in _NAME_JOINERS or unicodedata.category(c) in ("Mn", "Mc", "Me") for c in word[:i]): return False - longest = max(longest, chunk) - return capitals >= 2 and longest >= 2 + return max(longest, chunk) >= 2 def written_as_a_name(text: str) -> bool: @@ -2389,7 +2389,7 @@ def end_of(i: int) -> int: #: particle starts a surname unit, and a suffix word stops it -- any #: suffix word, a wider stop than group's particle chain makes, which #: a suffix word ends only where a suffix run would start at it -#: (decisions/P2, #1177); #1259 left this count as it was. A word +#: (decisions/P2, #1177). A word #: that is ALSO title vocabulary ('Freiherr', 'St') LEADING the part is #: not a particle here: in front of a name it reads as the title it #: also is (rules/H1), so 'Freiherr von Berg, PhD' keeps its title, @@ -3227,9 +3227,9 @@ def effective_script(text: str) -> Script | None: return Script.HIRAGANA # a Cyrillic word with a hyphen or an apostrophe inside it (#1237); # translate is C-level, so a token with no joiner costs no frame - joined = normalized.translate(_DROP_CYRILLIC_JOINERS) + joined = normalized.translate(_DROP_NAME_JOINERS) if (joined != normalized and normalized[0] in _CYRILLIC_LETTERS - and normalized[-1] not in _CYRILLIC_JOINERS + and normalized[-1] not in _NAME_JOINERS and _SCRIPT_MATCHERS[Script.CYRILLIC](joined)): return Script.CYRILLIC return None diff --git a/tests/v2/test_layering.py b/tests/v2/test_layering.py index 150e0bdb0..435d7b36f 100644 --- a/tests/v2/test_layering.py +++ b/tests/v2/test_layering.py @@ -725,7 +725,9 @@ def test_the_check_finds_a_tool_read_through_an_alias( #: ambiguous suffix halves dropped from the peel as subsets, 202 -> 200; #: #1369's capitals vote asking the base parse where a family word is #: a listed title, its `sets =` binding and the two title sets it -#: reads, 200 -> 203); +#: reads, 200 -> 203; the 3.1 simplify pass folding T8's two copies +#: of the unambiguous title-or-suffix test after a glued stop into +#: `_vocab._claimed_after_the_stop`, 203 -> 198); #: the tools' first 20 are 18 #: attribute loads, every tool scanned, and config_diff.py's #: `sets =` binding and the roster `getattr` through it (its @@ -747,7 +749,7 @@ def test_the_check_finds_a_tool_read_through_an_alias( #: `_lexicon._fields_of` from 4i-b until 4i-c retired it. #: A reader added through `_sets` moves these, and they are re-taken #: then: they count what the check would refuse with the move undone. -_UNGUARDED_READS = {"library": 203, "tools": 28} +_UNGUARDED_READS = {"library": 198, "tools": 28} def test_the_check_refuses_every_read_4i_a_moved() -> None: From 10ac5aa51501d699c0a690a39f88599a51fa8382 Mon Sep 17 00:00:00 2001 From: Derek Gulbranson Date: Mon, 16 Nov 2026 00:46:08 -0800 Subject: [PATCH 2/2] Tidy is_capitals_word's spacing and indentation after the joiner fold Co-Authored-By: Claude Opus 5.5 --- nameparser/_pipeline/_vocab.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/nameparser/_pipeline/_vocab.py b/nameparser/_pipeline/_vocab.py index 0faa480f3..7526ae832 100644 --- a/nameparser/_pipeline/_vocab.py +++ b/nameparser/_pipeline/_vocab.py @@ -2145,7 +2145,6 @@ def in_any_wordlist(n: str, lexicon: Lexicon) -> bool: if f not in ("surnames", "bound_given_names")) - def is_capitals_word(text: str) -> bool: """Whether TEXT is a name written in capitals, as rules/O9 reads one: two or more letters in capitals ending the word, after any @@ -2182,8 +2181,8 @@ def is_capitals_word(text: str) -> bool: return False # a full stop, slash, digit, bracket or caseless letter # i is 0 where no lowercase prefix stopped the walk if i and not all(c.isalpha() or c in _NAME_JOINERS - or unicodedata.category(c) in ("Mn", "Mc", "Me") - for c in word[:i]): + or unicodedata.category(c) in ("Mn", "Mc", "Me") + for c in word[:i]): return False return max(longest, chunk) >= 2