diff --git a/nameparser/_lexicon.py b/nameparser/_lexicon.py index 451ab80a6..ceddd17a5 100644 --- a/nameparser/_lexicon.py +++ b/nameparser/_lexicon.py @@ -22,9 +22,13 @@ from types import FrameType, MappingProxyType, ModuleType from typing import TYPE_CHECKING, Any, NamedTuple, cast -#: Vocabulary set fields, in declaration order. add()/remove() operate -#: on exactly these and reject capitalization_exceptions (its entries -#: are pairs -- use dataclasses.replace); __or__ unions these AND merges +#: Vocabulary set fields, in declaration order: the 2.x `Lexicon` +#: fields but the masks, and `given_names` (3.0). Since 3.0's 4i-b +#: (#754) only the two lists (`_LIST_FIELDS`) are still fields, the +#: rest being the sets a compile of readings gives (`_SET_FIELDS`); +#: add() and remove() take a word and its reading's kind, never one of +#: these names, and ``|`` unions the lists, concatenates the edit logs +#: (which is how every other set is joined) and merges #: capitalization_exceptions right-biased. _VOCAB_FIELDS = ( "titles", "given_name_titles", "suffix_acronyms", "suffix_words", @@ -370,9 +374,10 @@ def __init__(self, key: str, normalized_key: str, value: str) -> None: f"capitalization_exceptions value {value!r} for key {key!r} " f"does not spell the key's letters and digits: a value " f"is a case mask, the key's own letters and digits " - f"recased -- e.g. " - f"capitalization_exceptions=(({normalized_key!r}, " - f"{self.offered!r}),)") + f"recased -- e.g. dataclasses.replace(lexicon, " + f"capitalization_exceptions=(*lexicon." + f"capitalization_exceptions, ({normalized_key!r}, " + f"{self.offered!r})))") def __reduce__( self, @@ -1126,7 +1131,7 @@ def _edit_props(kind: str, props: Mapping[str, object]) -> _Props: if prop == "after_particle" and kind == "family": raise ValueError( "after_particle names a given name written behind a " - "particle (rules/O7), so only a given reading takes it: " + "particle (rules/P10), so only a given reading takes it: " "write add(word, kind='given', after_particle=True)") if prop not in allowed: raise ValueError( @@ -1906,24 +1911,27 @@ class LexiconReading: as, in the vocabulary files' terms (decisions/vocabulary-model, 2026-11-02 #754, item 2). - ``kind`` is a vocabulary kind as the language files write it - (``"office"``, ``"credential"``, ``"preposition"``, ``"given"``), - finer than :class:`ReadingKind`, which is the parse's; ``category`` - its category (``"title"``, ``"suffix"``, ``"particle"``, - ``"conjunction"``, ``"bound_given"``, ``"relation"``, ``"name"``); - ``properties`` its behavioral properties as sorted ``(name, value)`` - pairs, spelled as the files spell them (``("addresses", "given")``), - a list value a sorted tuple; ``languages`` the BCP 47 tags of the - shipped files holding it, sorted, empty for a reading a caller - added. Whether the parse READ a word this way is the parse's + Whether the parse READ a word this way is the parse's question, :attr:`Token.reading`: a title reading beside a ``given`` one is a title only inside a title phrase (rules/H9). Added in 3.0.""" + #: The word, folded as the lexicon stores it (``dr``). text: str + #: A vocabulary kind as the language files write it (``"office"``, + #: ``"credential"``, ``"preposition"``, ``"given"``), finer than + #: :class:`ReadingKind`, which is the parse's. kind: str + #: The kind's category (``"title"``, ``"suffix"``, ``"particle"``, + #: ``"conjunction"``, ``"bound_given"``, ``"relation"``, + #: ``"name"``). category: str + #: The behavioral properties as sorted ``(name, value)`` pairs, + #: spelled as the files spell them (``("addresses", "given")``), a + #: list value a sorted tuple. properties: tuple[tuple[str, Any], ...] = () + #: The BCP 47 tags of the shipped files holding the reading, sorted; + #: empty for a reading a caller added. languages: tuple[str, ...] = () def __post_init__(self) -> None: @@ -2373,7 +2381,7 @@ def words(self, *, kind: str, **properties: object) -> tuple[str, ...]: address a person by the given name). ``same_as`` matches a reading naming every word given among the words it is a spelling of (``words(kind="given", same_as="muhammad")`` lists - ``md``, ``mohd`` and ``moh``, each a spelling of several). A + ``md``, ``mohd`` and ``moh`` among others). A phrase the lexicon holds whole (``"z domu"``) is one entry. Added in 3.0.""" k = _check_kind(kind, "words") @@ -2445,12 +2453,12 @@ def add(self, *words: str, kind: str | None = None, given readings, so the word keeps no plain given reading and its link counts written bare, where a word the vocabulary also holds as a name of its own counts only - written with its period), and ``short_for=[...]`` on a - ``familiar`` reading, the longer given names a familiar + written with its period. ``short_for=[...]`` on a + ``familiar`` reading names the longer given names a familiar form stands for, which name matching reads as a ``familiar-form`` where that outcome is accepted and no parse reads (``add("max", kind="familiar", - short_for=["maxwell"])``), which EXTENDS the longer names + short_for=["maxwell"])``); it EXTENDS the longer names the word's shipped familiar readings list, in a reading of the caller's own that names no file, rather than replacing them (unlike an add of any other kind the word holds); to @@ -2464,7 +2472,7 @@ def add(self, *words: str, kind: str | None = None, reads as an ``alternate-spelling`` where that outcome is accepted and no parse reads (``add("olha", kind="spelling", spelling_of=["olga"])``), extending as a - familiar reading does; a property + familiar reading does. A property given its unwritten value (``None``, ``False``) is removed. Where the word holds a reading of `kind` already, the add updates its properties in every file holding it; otherwise it adds the caller's own reading, which names no diff --git a/nameparser/_match.py b/nameparser/_match.py index cd2bcaf9e..ab2c50f25 100644 --- a/nameparser/_match.py +++ b/nameparser/_match.py @@ -19,8 +19,10 @@ (for `Policy()`, which the repr compares a parser's policy with) and `_lexicon` (for `_normalize`, which folds a hyphen half before it is looked up among -the particles, and `Lexicon.default()`, which the repr compares a -parser's lexicon with), `_pipeline._vocab` (for `_HYPHEN_CHARS`, the +the particles, `Lexicon.default()`, which the repr compares a +parser's lexicon with, `_fold` and `_forms`, the fold and the folded +forms the match compares and keys a word by, and `FULL_STOPS`, the +full stops a word written short ends in), `_pipeline._vocab` (for `_HYPHEN_CHARS`, the hyphens the pipeline joins two names with, every one of which the match reads as the hyphen-minus, `_HYPHENS`, the pattern a word is cut at them by, and `in_initialless_script`, the scripts that @@ -74,23 +76,53 @@ class Outcome(StrEnum): `Matching.other_readings`, and the reading used is named in `MatchResult.left_alternative` and `right_alternative`.""" + #: The two texts are equal as written. SAME = "same" + #: Equal once case, accents, full stops and apostrophes are folded + #: away, each joining hyphen is read as the hyphen-minus, and a + #: letter a keyboard lacks is read as typed. FOLDED = "folded" + #: Equal once folded and stripped of spaces and hyphens, save where + #: both are initials alone (``LaRussa`` / ``La Russa``). JOINED = "joined" + #: Spellings the vocabulary lists as one (``Wm.`` / ``William``). LISTED_SPELLING = "listed-spelling" + #: The family names, or the maiden names, agree without their + #: particles (``de la Vega`` / ``Vega``). PARTICLES_ASIDE = "particles-aside" + #: One family or maiden name's words are among the other's, or + #: listed spellings of them, save where both are initials alone. PART_OF_OTHER = "part-of-other" + #: An initial against a name, outside the family name, and a given + #: name of capitals against the names that spell it (``JP`` / + #: ``John Paul``). INITIAL = "initial" + #: One role written in initials alone on both sides, the same + #: initials in the same order. INITIALS_AGREE = "initials-agree" + #: A middle name, nickname or maiden name on one side only. ONE_SIDE = "one-side" + #: A generation on one side only. GENERATION_ONE_SIDE = "generation-one-side" + #: Titles and credentials, which never conflict. NOTED = "noted" + #: Two given names the vocabulary lists as one name spelled two + #: ways (``Yuliya`` / ``Iuliia``). Not accepted by default. ALTERNATE_SPELLING = "alternate-spelling" + #: Two given names the vocabulary lists as a familiar-form pair + #: (``Bill`` / ``William``). Not accepted by default. FAMILIAR_FORM = "familiar-form" + #: The family name written as an initial. Not accepted by default. FAMILY_INITIAL = "family-initial" + #: A given name on one side only. Not accepted by default. GIVEN_ONE_SIDE = "given-one-side" + #: A given name against the first half of a hyphenated one + #: (``Hong`` / ``Hong-Yi``). Not accepted by default. HYPHENATED_PART = "hyphenated-part" + #: A name in a different role on each side, recorded in + #: :attr:`MatchResult.across`. Not accepted by default. ACROSS_ROLES = "across-roles" + #: The two texts contradict each other; never accepted. CONFLICT = "conflict" @property @@ -110,8 +142,11 @@ def strength(self) -> int: class Side(StrEnum): """Which side of a comparison carried more of the role's text.""" + #: The left name carried more of the role's text. LEFT = "left" + #: The right name carried more of the role's text. RIGHT = "right" + #: Neither name carried more than the other. NEITHER = "neither" @@ -125,10 +160,15 @@ class RoleMatch: more is the one whose name held both the role and the cross role the match used (`J. Edgar Hoover` / `Edgar Hoover`: left).""" + #: The role compared. role: Role + #: How the two sides' text of the role compares. outcome: Outcome + #: The left name's text of the role. left: str + #: The right name's text of the role. right: str + #: Which side carried more of the role's text. more: Side __getstate__ = _guarded_getstate @@ -146,10 +186,15 @@ class CrossRoleMatch: other (`across-roles`): the left name's role and text, the right name's role and text, and the outcome of comparing the two texts.""" + #: The left name's role the match used. left_role: Role + #: The right name's role the match used. right_role: Role + #: The outcome of comparing the two texts. outcome: Outcome + #: The left name's text in ``left_role``. left: str + #: The right name's text in ``right_role``. right: str __getstate__ = _guarded_getstate @@ -183,10 +228,20 @@ class MatchResult: A result has no truth value: `bool(result)` raises TypeError, a conflict being a result too, so test `result.consistent`.""" + #: Whether nothing in the two names contradicts the match under + #: the accepted outcomes. consistent: bool + #: One :class:`RoleMatch` per :class:`Role`, in ``Role`` order. roles: tuple[RoleMatch, ...] + #: The :class:`CrossRoleMatch` behind each role read + #: ``across-roles``, in ``Role`` order of the role it resolved; + #: empty unless ``across-roles`` is accepted. across: tuple[CrossRoleMatch, ...] = () + #: The :class:`Ambiguity` whose other reading the table used for the + #: left name, or ``None`` where it is read as parsed (always ``None`` + #: unless ``other_readings`` is on). left_alternative: Ambiguity | None = None + #: The same for the right name. right_alternative: Ambiguity | None = None __getstate__ = _guarded_getstate diff --git a/nameparser/_parser.py b/nameparser/_parser.py index 946a8f4da..4d6be76d1 100644 --- a/nameparser/_parser.py +++ b/nameparser/_parser.py @@ -1,7 +1,8 @@ """Parser and the module-level parse() for the 2.0 API. -Layering: sits on _types/_lexicon/_policy/_locale/_pipeline; never -imports _render (enforced by tests/v2/test_layering.py). +Layering: sits on _types/_lexicon/_policy/_locale/_pipeline, and imports +_match, _suggest and _reading_index at call time only; never imports +_render (enforced by tests/v2/test_layering.py). _default_parser is THE one sanctioned module-level global: a functools.cache'd frozen Parser over default config. @@ -359,9 +360,9 @@ def suggest(self, names: Iterable[str]) -> Suggestion: letters ends at least two names and at least half of the names ending in letters (Nepal's ``B K``), and a group decided so casts no trailing-initial vote on its order; a group never turns - it off, nor turns it on under a base reading names family first - or folding every middle into the family, where it would change - no name. ``capitals_as_family`` (rules/O9) is turned on where + it off, nor turns it on under a base reading names family first, + where letters ending a name are never read as its family. + ``capitals_as_family`` (rules/O9) is turned on where at least two names, and more than two thirds of the names with evidence either way, write the family in capitals: the rule, asked of the name parsed with the switch on, reads as its family diff --git a/nameparser/_pipeline/__init__.py b/nameparser/_pipeline/__init__.py index 9c91ba088..0a0f56bf1 100644 --- a/nameparser/_pipeline/__init__.py +++ b/nameparser/_pipeline/__init__.py @@ -1,8 +1,8 @@ """The 2.0 parse pipeline: pure stages folded over ParseState. -Stage names and ParseState are NOT public API. The stage list is data; -runners other than the plain fold (explain(), parse_all()) arrive in -2.x minors without changing any stage signature. +Stage names and ParseState are NOT public API. The stage list is data, +so a runner other than the plain fold could be added without changing +any stage signature. Layering: imports only nameparser._pipeline.* (enforced by tests/v2/test_layering.py). diff --git a/nameparser/_pipeline/_assemble.py b/nameparser/_pipeline/_assemble.py index 0760fd762..d71635966 100644 --- a/nameparser/_pipeline/_assemble.py +++ b/nameparser/_pipeline/_assemble.py @@ -541,7 +541,7 @@ def assemble(state: ParseState) -> ParsedName: reading: Reading | None = None if role is Role.SUFFIX: # a suffix ends a particle's run: the family can resume - # behind it ('Hasan' in 'bin Ahmad Jr. Hasan, Ali') + # behind it ('Hasan' in 'bin Ahmad III Hasan, Ali') run_field = None kind, source = suffix_kind(t.text, tags) if (source is ReadingSource.VOCABULARY diff --git a/nameparser/_pipeline/_assign.py b/nameparser/_pipeline/_assign.py index a061fab19..205f9c35f 100644 --- a/nameparser/_pipeline/_assign.py +++ b/nameparser/_pipeline/_assign.py @@ -5,7 +5,9 @@ once, after P3's joins and before the particle chain (#614), which the main segment's placement takes rather than peeling again, save where group's joins left no name word in front of it; and interpunct_offsets, -whose 间隔号 keeps a transcription in its declared order (rules/W4). +whose 间隔号 keeps a transcription in its declared order (rules/W4); +and extracted, whether a set-apart clause stands beside the name +(N3's single-name rule and the sites that follow it). Produces: tokens with roles set on every main-stream token, and the folded-middle and attached tags on the particles P6's attachment joins to the family after a family comma (#613; the attached tag, 3.0's 4c, @@ -17,14 +19,18 @@ piece of a two-part comma name, and Policy.script_orders (#271, which overrides it when every name piece is written wholly in one script, or in the Han/Hiragana/Katakana repertoire the #272 kana license shares -across pieces); token/piece tags; Lexicon only through tags already -applied by classify (plus the leading-title period rule), and +across pieces); token/piece tags; Lexicon through tags already +applied by classify (plus the leading-title period rule), save the +four suffix sets (suffix_words, suffix_acronyms and their ambiguous +sets), which the walk over the given part after a family comma reads +through _vocab.is_suffix_lenient (`_reads_as_a_trailing_suffix`), and Lexicon.given_name_titles, which an ambiguity's alternative asks for rules/P5's given-name-title licence; and Lexicon.title_phrases, titles and titles_ambiguous through _vocab.in_a_title_phrase, for rules/H9's TITLE_OR_NAME report on a contested word opening the name. -Implements rules H2, H4, H5, H6, H7, H8, N3, O4, O5, S10, W4, and P6 after a family comma, +Implements rules H2, H4, H5, H6, H7, H8, H9, H10, C9, N3, O4, O5, P9, +S8, S10, S12, W4, and P6 after a family comma, of docs/design/rules/, each cited at its code below. Ports v1's assignment loops. NO_COMMA (per name_order): @@ -976,7 +982,7 @@ def _reads_as_a_trailing_suffix(piece: Sequence[int], marks an abbreviation, is name material -- so 'Smith, John V.' is middle 'V.' where 'Smith, John V' stays suffix 'V' (v1 parity, #144). Only behind a NAME word: behind a suffix the credential run - owns it, and 'Smith, John PhD I.' keeps suffix 'PhD, I.'. + owns it, and 'Smith, John PhD I.' keeps suffix 'PhD I.'. The period is the whole carve-out. is_initial_shaped would be redundant beside it: the caller only consults this where @@ -1757,7 +1763,7 @@ def reads_as_a_suffix(m: int, titled: frozenset[int]) -> bool: # reading now (#613), so the walk here never meets # either: a last piece # that is unambiguously suffix-shaped is a suffix, where v1 - # made it the given ('Andrews, M.D.', 'Smith, Dr. Jr.'; + # made it the given ('Smith, Dr. Jr.'; # classified fix(comma-family)), a segment whose only # non-title piece is a suffix piece holding no name word; # and a credential opening the segment makes it the diff --git a/nameparser/_pipeline/_classify.py b/nameparser/_pipeline/_classify.py index 5992f7f84..c705c2f91 100644 --- a/nameparser/_pipeline/_classify.py +++ b/nameparser/_pipeline/_classify.py @@ -13,9 +13,12 @@ one_case -- whether the name's own words are written in one case, recorded for the later stages that read it (#289/#516) and left alone where an earlier stage already asked. -Reads: every Lexicon vocabulary field except surnames and -honorific_tails, which script_segment consumes upstream, and -given_names, which only post_rules reads (rules/O6); and the kinds +Reads: every Lexicon vocabulary field except given_names, which only +post_rules and assemble read (rules/O6) -- surnames and +honorific_tails, which script_segment consumes upstream, only through +helpers: the caps shape's unlisted test (`_vocab.in_any_wordlist`) +reads both, and `_vocab.period_joined_credential` honorific_tails; +and the kinds of its suffix words and particles (Lexicon's generation_words, credential_words, honorific_words and patronymic_particles, internal sets, 3.0) and the @@ -26,7 +29,9 @@ written behind a particle (particle_given_names, #704) and the two-word given names a bound word completes into (bound_phrases, #694) and the titles a run of single letters may spell -(dotted_titles, rules/H10, #490); and, since +(dotted_titles, rules/H10, #490) and the saint particles a word glued +at its full stop is cut behind (saint_particles, through +`_vocab.glued_saint_cut`); and, since 2.4, Policy.unlisted_dotted_suffixes and Policy.unlisted_caps_suffixes, which decide whether an UNLISTED dotted or all-caps token joins the ambiguous credential class by SHAPE (#516) -- the all-caps half here @@ -43,23 +48,25 @@ `initial`, which is the whole of #320). Tags emitted -- stable (API): "particle", "conjunction", "initial"; -namespaced (unstable): "vocab:title", "vocab:given-title", -"vocab:after-given-title", "vocab:title-ambiguous", +namespaced (unstable), kept on the published token: "vocab:title", +"vocab:given-title", "vocab:after-given-title", +"vocab:title-ambiguous", "vocab:dotted-title" (a run of single letters +spelling a title the lexicon marks `dotted`, rules/H10, #490), "vocab:suffix", "vocab:suffix-word", "vocab:suffix-ambiguous", -"vocab:suffix-word-ambiguous", "vocab:agnomen", -"vocab:generation-word", "vocab:credential-word", -"vocab:honorific-word", "vocab:patronymic", "vocab:trailing-title", -"vocab:joined-title" and "vocab:chain-title" (read by the later stages -and dropped by assemble, Token.reading carrying the kind out, save the -last three, which mark no kind), "vocab:title-case-name" (a suffix word whose -Title case leans to the name, rules/S6, kept on the published token), +"vocab:suffix-word-ambiguous", "vocab:agnomen", "vocab:title-case-name" +(a suffix word whose Title case leans to the name, rules/S6), "vocab:particle-ambiguous", "vocab:bound-given", -"vocab:given-abbreviation", "vocab:shared-name" (which rules/P10, O6 -and O7 read), "vocab:particle-given" (which P10 and O6 read) and -"vocab:bound-phrase" (on a bound word and the word after it being a -listed pair, which P12 joins and O6 counts once, #694), each -dropped by assemble and carrying no kind out, "vocab:maiden-marker", -"vocab:maiden-marker-cont"; in a namespace of its own, +"vocab:given-abbreviation", "vocab:maiden-marker" and +"vocab:maiden-marker-cont" (a marker group drops leaves no token; one +read as a word keeps its tag); namespaced, read by the later stages and dropped +by assemble (`_assemble._KIND_TAGS`): "vocab:generation-word", +"vocab:credential-word", "vocab:honorific-word" and "vocab:patronymic", +Token.reading carrying the kind out, "vocab:trailing-title", +"vocab:joined-title" and "vocab:chain-title", which mark no kind, +"vocab:shared-name" (which rules/P10, O6 and O7 read), +"vocab:particle-given" (which P10 and O6 read) and "vocab:bound-phrase" +(on a bound word and the word after it being a listed pair, which P12 +joins and O6 counts once, #694); in a namespace of its own, "shape:acronym"; and in another, "split:credential" and "split:member", written on the first word of a credential split across a space (`_vocab.split_pair`) to name the piece the pair merges into: diff --git a/nameparser/_pipeline/_extract.py b/nameparser/_pipeline/_extract.py index 0e9364c9a..e2f0be7a9 100644 --- a/nameparser/_pipeline/_extract.py +++ b/nameparser/_pipeline/_extract.py @@ -20,7 +20,10 @@ `set_apart` (rules/S1) Lexicon.suffix_words / suffix_words_ambiguous / suffix_acronyms / suffix_acronyms_ambiguous / titles / title_modifiers / title_styles / given_name_titles / -after_given_titles. +after_given_titles, honorific_tails (through +`_vocab.period_joined_credential`) and generation_words and +honorific_words (through `_vocab.settles_a_member`, the words that +do NOT settle a member beside them, rules/S1). Implements rules N1, N2, S1, M1 and M3 of docs/design/rules/ (the #273 matching mechanism); each is cited at its code below. One scan diff --git a/nameparser/_pipeline/_group.py b/nameparser/_pipeline/_group.py index 2e8b2e0bd..be7ffd09a 100644 --- a/nameparser/_pipeline/_group.py +++ b/nameparser/_pipeline/_group.py @@ -11,7 +11,11 @@ segment and dropping its delimiter cores before any join, plus the SUFFIX_OR_NAME ambiguities that decision reports, those the particle chain and a maiden clause report on a trailing member they take into the name -(an ambiguous acronym, or since #718 a declined numeral), and the +(an ambiguous acronym, or since #718 a declined numeral), the +PARTICLE_OR_GIVEN report the particle chain makes where it chains an +ambiguous particle with nothing but leading titles in front of it +(`St van Johnson`, `Freiherr von der Berg`; `Vincent van Gogh` and +`Dr. Van Johnson` report nothing here), and the caps shape's acronym tags on a bound all-caps word (#564); pieces + piece_tags per segment (runs of token indices -- tokens are NEVER joined into strings: the @@ -37,7 +41,8 @@ per-parse state that dissolves with the state (v1 kept per-parse sets for the same reason). -Implements rules P2, P3, P4, P12 and M2, S2's trailing read (#614), C1's +Implements rules P2, P3, P4, P12, P13, M2 and C10 (a delimiter core +parting a tail segment), S2's trailing read (#614), C1's decision through _comma, and the group half of M1 (#329: the marker dropped inside EXTRACTED maiden @@ -59,8 +64,9 @@ with them. is_prefix_piece and is_conj_piece followed in #617, with the merge and rules/P3's connective joins (join_connectives), when the comma decision's own copy of those joins was folded into them. -What remains defined here is group's own: _is_rootname and -_is_maiden_marker_piece. +What remains defined here is group's own: the piece predicates +_is_rootname, _is_maiden_marker_piece, _is_lone_letter and +_is_name_word, beside the helpers of its joins and its maiden take. """ from __future__ import annotations diff --git a/nameparser/_pipeline/_pieces.py b/nameparser/_pipeline/_pieces.py index 02cf24fdd..80ab75204 100644 --- a/nameparser/_pipeline/_pieces.py +++ b/nameparser/_pipeline/_pieces.py @@ -567,10 +567,11 @@ def starts_a_credential_run(piece: Sequence[int], ptags: Set[str], other is the vocabulary-against-shape split nameparser/AGENTS.md's spelling sweep names (#603 found it, 'Smith, John Ph. D. Jones' keeping middle 'Jones' where 'Smith, John PhD Jones' reads suffix - 'PhD Jones'). The no-comma spelling is not reached: `run_start` - asks only of the pieces `peel_walk` keeps, and the walk drops the - merged piece, so 'John Smith Ph. D. Jones' still reads family - 'Jones'. + 'PhD Jones'). Without a comma `peel_walk` leaves the merged piece + out of the pieces `run_start` walks, so `run_start` asks this of + the piece in front of a kept one itself (#827): 'John Smith Ph. D. + Jones' reads suffix 'Ph. D. Jones' as 'John Smith PhD Jones' reads + 'PhD Jones'. A roman numeral of two or more letters starts it where `_vocab.reads_as_generation` reads it as the generation, with @@ -862,7 +863,7 @@ def segment_suffix_reading(pieces: Sequence[Sequence[int]], suffix 'MA'). Only the LEAN reaches here on its own: a token admitted to the class by SHAPE takes the count instead, which `_comma.decide` takes and hands in as `licensed`, below ('Smith, - A.B.' -> given 'A.B.', one name word being no count). + XYZ' -> given 'XYZ', one name word being no count). A listed member ANCHORED by an unambiguous credential in front of it in the same run reads as a credential too, whatever its writing @@ -1231,7 +1232,7 @@ def credential_at_the_given_slot( in front of it in the same run (`credential_anchors`) makes it the credential whatever its writing says, a particle member included -- a degree in front outranks P6's attachment, as the capitals do - ('doe, jane v phd do' reads suffix 'v phd do'). Only the caller + ('doe, jane v phd do' reads suffix 'phd do'). Only the caller knows the run, so it computes the anchor; `anchored` is a THUNK, asked last, so a member the writing already settles never pays for the walk. @@ -1509,7 +1510,7 @@ def peel_trailing(rest: Sequence[int], pieces: Sequence[Sequence[int]], one_case) # rules/S11: "the floor holds first" -- a generation word's # case may settle it as the suffix only where the name keeps - # a family word ('Pedro Junior fils' keeps family 'fils', + # a family word ('Pedro Jnr fils' keeps family 'fils', # Derek, #890); an acronym's capitals take it with none gated = AMBIGUOUS_WORD_TAG in tokens[piece[0]].tags if (lean == "credential" and (not gated or front >= second) diff --git a/nameparser/_pipeline/_post_rules.py b/nameparser/_pipeline/_post_rules.py index c1d95740f..9f25ee68b 100644 --- a/nameparser/_pipeline/_post_rules.py +++ b/nameparser/_pipeline/_post_rules.py @@ -45,10 +45,14 @@ carries no tag there, S13, through `_vocab.dotted_member`), and for S1's set-apart clause Lexicon.suffix_words directly and, through `_vocab.set_apart_kind` and `set_apart`, Lexicon.suffix_words_ambiguous, suffix_acronyms, titles, -title_modifiers, title_styles and after_given_titles. - -Implements rules S1, S13, H1, M4, P1, P6 (its no-comma site), P10, O1, O2, -O6, O7, O8, O9, O3 and R1 of docs/design/rules/; each is cited at its code below, and +title_modifiers, title_styles, after_given_titles and honorific_tails +(through `_vocab.period_joined_credential`), with generation_words +and honorific_words, the suffix words that do not settle a member +(`_vocab.settles_a_member`). + +Implements rules S1, S13, H1, M4, P1, P6 (its no-comma site), P10, P11, +O1, O2, O6, O7, O8, O9, O3, R1, R10, R11 and W5's surname pair of +docs/design/rules/; each is cited at its code below, and H1/P1/O1/O2's history lives in docs/design/decisions/. `suffix_entries` is the R1 entry pass as a state-in/state-out function, for Parser.revise to run over a forced-role sub-parse @@ -96,7 +100,7 @@ #: entry pass below). These three roles render into fields other than #: the name and the suffix, so a run of #: post-nominals is not parted by them -- 'Smith, MD Dr. PhD', -#: 'Smith, MD "Doc" PhD' and 'Smith, MD nee Jones PhD' are each one +#: 'Smith, MD "Doc" PhD' and 'Smith, MD (nee Jones) PhD' are each one #: entry. GIVEN/MIDDLE/FAMILY are name words and part it. _RENDERS_ELSEWHERE = frozenset({Role.TITLE, Role.NICKNAME, Role.MAIDEN}) @@ -1272,8 +1276,8 @@ def post_rules(state: ParseState) -> ParseState: # rather than a boundary: this guard counts GIVEN tokens where # H1 counts nothing (it tests which roles are unoccupied), so a # name word another rule joined counts as several here and the - # rule declines -- `Dr. Dean of Chemistry` reads family, while - # `Dean of Chemistry née Jones` keeps given 'Dean of Chemistry'. + # rule declines -- `Dr. Mary and Jane` reads family, while + # `Mary and Jane née Jones` keeps given 'Mary and Jane'. # rules/P3 says a joined part is one name word wherever # another rule counts them, so the two disagree; widening moves # no corpus name and is not this change's to make diff --git a/nameparser/_pipeline/_segment.py b/nameparser/_pipeline/_segment.py index f10ecaf6b..c76fc21e1 100644 --- a/nameparser/_pipeline/_segment.py +++ b/nameparser/_pipeline/_segment.py @@ -11,7 +11,11 @@ and COMMA_STRUCTURE ambiguities for unrecognized extra segments (a part of title and suffix words is recognized, #603). Reads: for C2's flag on a part past the second comma only: Lexicon -suffix vocabulary and Policy through _vocab.is_wholly_suffix +suffix vocabulary (the four suffix sets; generation_words and +honorific_words, the suffix words that do not settle a joined member; +title_case_name_words, +whose Title case leans to the name; and honorific_tails, through +_vocab.period_joined_credential) and Policy through _vocab.is_wholly_suffix (Policy.lenient_comma_suffixes picks the lenient or strict token test; Policy.extra_suffix_delimiters makes a delimiter-core token transparent, as the built-in cores are), with the credential lean the lazy case gate supplies @@ -24,7 +28,8 @@ title with a delimiter glued to it (rules/C10), for a part of titles and suffixes (#603). -Implements rule C2 of docs/design/rules/, and C1's segmentation; +Implements rules C2 and C10 (a title with a delimiter glued to it) of +docs/design/rules/, and C1's segmentation; C1's decision is `_comma.decide`'s. History in decisions/C1. """ from __future__ import annotations diff --git a/nameparser/_pipeline/_tokenize.py b/nameparser/_pipeline/_tokenize.py index dcdd267da..83cddc6b5 100644 --- a/nameparser/_pipeline/_tokenize.py +++ b/nameparser/_pipeline/_tokenize.py @@ -1,17 +1,21 @@ """Stage: tokenize. Consumes: original, masked (regions to skip), extracted (regions that -tokenize with a pre-set role). +tokenize with a pre-set role), and ambiguities (extract's +UNBALANCED_DELIMITER reports, which carry a character offset). Produces: tokens (span-sorted WorkTokens; text always == original slice), comma_offsets (segmentation points of the main stream; a comma there is never a token, one inside an extracted region is word text), interpunct_offsets (间隔号 and fullwidth-stop transcription markers, #298, -#1312; never tokens). +#1312; never tokens), and ambiguities, each report extract left +carrying a character offset rewritten to the index of the token +holding that character (no index where the offset is masked). Reads: Policy.strip_emoji, Policy.strip_bidi. -Implements rules T1, T2, T3 and T6 of docs/design/rules/, cited at -their code below. There is NO text-rewriting normalize stage: all -four are character-classification rules, so spans always index the +Implements rules T1, T2, T3 and T6 of docs/design/rules/, and N1's +comma kept inside a clause, cited at their code below. There is NO +text-rewriting normalize stage: the four T rules are +character-classification rules, so spans always index the original exactly as given (v1 contrast: decisions/T1). Beside the stage function, `_ignorable` is shared: extract asks it diff --git a/nameparser/_pipeline/_vocab.py b/nameparser/_pipeline/_vocab.py index 7526ae832..cd248c3c3 100644 --- a/nameparser/_pipeline/_vocab.py +++ b/nameparser/_pipeline/_vocab.py @@ -1933,7 +1933,9 @@ class at all). Cheaper than `suffix_as_written(n, text, lexicon) or ...` would be here, and provably the same answer for UNDOTTED text: the Lexicon invariant that an ambiguous acronym is never also a suffix WORD - (`__post_init__`'s gate_bypassed check) and is never counted + (one suffix kind per word: the vocabulary build's check 4, which + `_lexicon._check_pool` runs on a caller's reading too) and is never + counted without periods once it IS one (`suffix_as_written`'s own exclusion) together kill that predicate's two disjuncts once text is known to hold no period. One frame (`_normalize`) on the common diff --git a/nameparser/_render.py b/nameparser/_render.py index 2647b7bfa..d18351deb 100644 --- a/nameparser/_render.py +++ b/nameparser/_render.py @@ -369,7 +369,9 @@ def _first_letter(text: str) -> str: def initials(name: ParsedName, spec: str, delimiter: str, separator: str) -> str: - """First letter of each contributing token per group, v1 semantics: + """First letter of each contributing token per group (one per + letter of a word written as a run of initials, rules/R3, #1296), + v1 semantics: delimiter follows each initial, separator sits between initials within a group. Each group is ordered the way its FIELD is ordered -- written order, except folded words, which initial diff --git a/nameparser/_suggest.py b/nameparser/_suggest.py index a4764b61e..ee10a805c 100644 --- a/nameparser/_suggest.py +++ b/nameparser/_suggest.py @@ -120,11 +120,22 @@ def fold(word: str) -> str: class Signal(StrEnum): """The evidence a single name offers about its writer's name order.""" + #: A family name written in capitals at one end of a name in mixed + #: case (``Mary SMITH``). CAPITALS = "capitals" + #: A trailing initial (``Smith J.``), counted only where enough of + #: the group's names end in initials. TRAILING_INITIAL = "trailing-initial" + #: A lowercase particle first or before the last word. PARTICLE = "particle" + #: A common romanized Chinese, Korean or Vietnamese surname as the + #: first or last word. SURNAME = "surname" + #: A common given name that is rarely a surname (``Emily``, not + #: ``Taylor``) as the first or last word. GIVEN_NAME = "given-name" + #: A patronymic one rule reads (Russian ``Petrovich``, Azerbaijani + #: ``Huseyn oglu``), the evidence on ``patronymic_rules``. PATRONYMIC = "patronymic" @@ -611,8 +622,10 @@ def _label(value: object) -> str: @dataclass(frozen=True, slots=True, init=False) class NameEvidence: """One input name and the votes it cast, read with the base - parser's lexicon. A name with a comma, no words or one word casts - none, and a name that casts none never disagrees with the group. + parser's lexicon. A name with a comma, save one whose comma only + post-nominals follow (``Kim Minjun, PhD``), and a name of no words + or one word cast none, and a name that casts none never disagrees + with the group. Order votes are one per NAME: the end the name's order signals agree on. A name whose order signals point at both ends is contested, casts no order vote and never disagrees on order. @@ -709,11 +722,20 @@ class SettingEvidence: value: SettingValue #: Whether the group's votes decided the value. decided: bool + #: The names whose vote is for ``value``. votes_for: int + #: The names whose vote is for another value. votes_against: int + #: The names whose signals point both ways on this setting, and so + #: cast no vote. contested: int + #: The names with no signal on this setting. no_evidence: int + #: The signals' own votes as ``(signal, vote, count)`` rows; a name + #: two signals read is in two of them. by_signal: tuple[tuple[Signal, Vote, int], ...] + #: Why the setting was decided or left undecided as it was, where + #: not empty. note: str = "" __getstate__ = _guarded_getstate @@ -782,7 +804,10 @@ class Suggestion: base: Parser #: The settings the group decided that differ from the base's. patch: PolicyPatch + #: One :class:`SettingEvidence` per setting considered. evidence: tuple[SettingEvidence, ...] + #: One :class:`NameEvidence` per input name, in input order, blanks and + #: duplicates included. names: tuple[NameEvidence, ...] __getstate__ = _guarded_getstate diff --git a/nameparser/_types.py b/nameparser/_types.py index 5cf039c07..3f9ea7650 100644 --- a/nameparser/_types.py +++ b/nameparser/_types.py @@ -839,7 +839,9 @@ class AmbiguityKind(StrEnum): #: A letter with no name word after it in its part -- nothing #: before a comma, a clause or the end, or only post-nominals and #: titles, as in "JOSE E", "rovira, i" or "jose e phd" -- connects - #: nothing, so it is read as an initial and not reported. Where + #: nothing, so it is read as an initial and not reported as this + #: kind (a name ending in one may still carry an ORDER report, + #: rules/O4, #1254). Where #: such a letter is a roman numeral at the end of the name the #: numeral fork reports it instead (SUFFIX_OR_NAME: "HENRY I", #: "john i phd"); one ending a comma part reports nothing diff --git a/nameparser/locales/zh.py b/nameparser/locales/zh.py index 42fa9d786..95e80a733 100644 --- a/nameparser/locales/zh.py +++ b/nameparser/locales/zh.py @@ -30,9 +30,9 @@ married double surname like 李林 would cut 李林伟 into 李林 + 伟. A coverage floor, not a census roster: extend by giving parser_for a base whose lexicon already carries the additions -- -``parser_for(locales.ZH, base=Parser(lexicon=Lexicon.default().add( -surnames={...})))``. (Adding to the finished parser's lexicon instead -is a silent no-op: Lexicon is frozen, so ``.add`` returns a NEW +``parser_for(locales.ZH, base=Parser(lexicon=Lexicon.default() | +Lexicon(surnames={...})))``. (Changing the finished parser's lexicon +instead is a silent no-op: Lexicon is frozen, so ``|`` returns a NEW lexicon that no parser is holding.) Declared deviations (mechanisms.md#LOCALE-PACKS-PURE-DATA): the diff --git a/tests/v2/test_lexicon.py b/tests/v2/test_lexicon.py index f4dad2ac0..579e146a8 100644 --- a/tests/v2/test_lexicon.py +++ b/tests/v2/test_lexicon.py @@ -146,6 +146,26 @@ def test_an_exception_value_that_does_not_spell_its_key_raises( assert repr(value) in str(caught.value) +def test_the_mask_error_offers_code_that_adds_the_mask_and_keeps_the_rest( +) -> None: + """The offered fix must RUN as pasted (AGENTS.md), and add to the + lexicon's masks as its two siblings' offers do: the 3.0 message + offered `capitalization_exceptions=(('phd', 'PHD'),)`, which pasted + into dataclasses.replace drops every shipped mask.""" + with pytest.raises(_MaskValueError) as caught: + Lexicon(capitalization_exceptions=(("phd", "Doctor"),)) + code = re.search(r"dataclasses\.replace\(.*?\)\)\)", str(caught.value)) + assert code is not None + base = Lexicon.default() + pasted = eval(code[0], {"dataclasses": dataclasses, # noqa: S307 + "lexicon": base}) + masks = pasted.capitalization_exceptions_map + assert masks["phd"] == caught.value.offered + assert {k: v for k, v in masks.items() if k != "phd"} == { + k: v for k, v in base.capitalization_exceptions_map.items() + if k != "phd"} + + def test_a_mask_may_recase_a_digit_key_unchanged() -> None: """#459 review: the mask compares ALPHANUMERICS (_lexicon._alnum), not letters alone, so a digit is part of what a value must spell @@ -199,15 +219,18 @@ def test_the_mask_error_offers_a_spelling_that_works_and_type_checks( run and to type-check. The field is annotated with what it STORES, a tuple of pairs, so a dict literal there is an arg-type error -- AGENTS.md's rule for actionable messages. The offered spelling is - the offending KEY recased upper, not a fixed example, so the two - constructions below use the spelling the 'jr' key's own error + the offending KEY recased upper, not a fixed example, so the + construction below uses the spelling the 'jr' key's own error offers, verbatim; mypy checks this file.""" - offered = "capitalization_exceptions=(('jr', 'JR'),)" + offered = ("dataclasses.replace(lexicon, capitalization_exceptions=(" + "*lexicon.capitalization_exceptions, ('jr', 'JR')))") with pytest.raises(ValueError) as caught: Lexicon(capitalization_exceptions=(("jr", "Junior"),)) assert offered in str(caught.value) - assert Lexicon(capitalization_exceptions=(('jr', 'JR'),)) \ - .capitalization_exceptions_map == {"jr": "JR"} + lexicon = Lexicon.default() + pasted = dataclasses.replace(lexicon, capitalization_exceptions=( + *lexicon.capitalization_exceptions, ('jr', 'JR'))) + assert pasted.capitalization_exceptions_map["jr"] == "JR" def test_the_mask_error_falls_back_when_upper_would_not_itself_validate( @@ -219,11 +242,14 @@ def test_the_mask_error_falls_back_when_upper_would_not_itself_validate( upper() would not itself spell the key's own letters.""" with pytest.raises(ValueError) as caught: Lexicon(capitalization_exceptions=(("straße", "STRASSE"),)) - offered = "capitalization_exceptions=(('straße', 'straße'),)" + offered = ("dataclasses.replace(lexicon, capitalization_exceptions=(" + "*lexicon.capitalization_exceptions, ('straße', 'straße')))") assert offered in str(caught.value) # pasted, the offered spelling constructs - assert Lexicon(capitalization_exceptions=(('straße', 'straße'),)) \ - .capitalization_exceptions_map == {"straße": "straße"} + lexicon = Lexicon.default() + pasted = dataclasses.replace(lexicon, capitalization_exceptions=( + *lexicon.capitalization_exceptions, ('straße', 'straße'))) + assert pasted.capitalization_exceptions_map["straße"] == "straße" def test_the_mask_error_echoes_the_callers_own_spelling_not_the_composed_one(