Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 30 additions & 22 deletions nameparser/_lexicon.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
59 changes: 57 additions & 2 deletions nameparser/_match.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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"


Expand All @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
11 changes: 6 additions & 5 deletions nameparser/_parser.py
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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
Expand Down
6 changes: 3 additions & 3 deletions nameparser/_pipeline/__init__.py
Original file line number Diff line number Diff line change
@@ -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).
Expand Down
2 changes: 1 addition & 1 deletion nameparser/_pipeline/_assemble.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 12 additions & 6 deletions nameparser/_pipeline/_assign.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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):
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading