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
30 changes: 20 additions & 10 deletions nameparser/_lexicon.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,14 +87,20 @@
# rules/T1: "at the edge the word is looked up without it"
# The zero-width non-joiner and joiner shape the letters on either side
# of them, so at a word's edge they shape nothing and are dropped when
# the word is looked up (#1335: `مهندس` typed with a ZWNJ after it is
# the title `مهندس`), with the edge full stops. Inside a word they stay
# the word is looked up, with the edge full stops (decisions/T1,
# #1335). Inside a word they stay
# (`آیت‌الله` is listed with its ZWNJ). Token text is never rewritten,
# which keeps the ZWJ Malayalam writes at a word's end.
_EDGE_JOINERS = "\u200c\u200d"
_NON_ASCII_EDGES = FULL_STOPS + _EDGE_JOINERS


def _a(kind: str) -> str:
"""The article a message writes before a reading's kind: ``an``
before a vowel and before ``honorific``, whose h is silent."""
return "an" if kind[:1] in "aeiou" or kind == "honorific" else "a"


def _normalize(word: str) -> str:
"""Lowercase, NFC-compose, strip whitespace and EDGE full stops
(FULL_STOPS, not the ASCII period alone -- #322), and in a non-ASCII
Expand Down Expand Up @@ -1027,7 +1033,7 @@ def _prop_value(kind: str, prop: str, value: object) -> object:
side = ("before" if _index_module().CATEGORY.get(kind) == "title"
else "after")
if value != side:
raise ValueError(f"attached on a {kind!r} reading must be "
raise ValueError(f"attached on {_a(kind)} {kind!r} reading must be "
f"{side!r} (a {'title peeled off the start' if side == 'before' else 'tail peeled off the end'} "
f"of a name token) or None, got {value!r}")
return value
Expand Down Expand Up @@ -1057,9 +1063,13 @@ def _prop_value(kind: str, prop: str, value: object) -> object:
# an empty list would leave `completes` unwritten, which
# joins behind ANY plain word, the widest reading; the build
# refuses it too (#1072)
cleared = ("joins it behind any plain word"
if prop == "completes"
else "leaves no listed word completing it")
raise ValueError(f"{prop} must list at least one word, got "
f"{value!r}; write {prop}=None to clear a "
f"list the word's reading has")
f"{value!r}; list the words it pairs with, or "
f"write {prop}=None to clear the list, which "
f"{cleared}")
if prop in ("completed_by", "completes") and any(" " in w for w in folded):
# rules/P12 joins two words: a bound word to the one word
# after it (completed_by), a bound_second word to the one
Expand Down Expand Up @@ -1196,7 +1206,7 @@ def _edit_props(kind: str, props: Mapping[str, object]) -> _Props:
"write add(word, kind='given', after_particle=True)")
if prop not in allowed:
raise ValueError(
f"a {kind} reading takes "
f"{_a(kind)} {kind} reading takes "
+ (", ".join(sorted(allowed)) or "no properties")
+ f"; got {prop!r}")
out[prop] = _prop_value(kind, prop, value)
Expand Down Expand Up @@ -1241,7 +1251,7 @@ def _make_edit(op: object, words: object, kind: object,
if " " in w and not (k == "birth_marker" or (
category == "title" and ("addresses", "given") in p)):
raise ValueError(
f"{w!r} is a phrase, which can never match as a {k}: only "
f"{w!r} is a phrase, which can never match as {_a(k)} {k}: only "
f"a birth_marker and a title with addresses='given' are "
f"matched as a whole run; add its words one by one")
# the build refuses attached on a title phrase: the glued-title
Expand Down Expand Up @@ -1782,7 +1792,7 @@ def _check_base(base: object) -> object:
if name not in ri.indexed(kind):
raise ValueError(
f"a Lexicon snapshot gives {word!r}'s {kind} reading "
f"the property {name!r}, which a {kind} reading "
f"the property {name!r}, which {_a(kind)} {kind} reading "
f"does not take in this release")
try:
hash(value)
Expand Down Expand Up @@ -1985,7 +1995,7 @@ class LexiconReading:
kind: str
#: The kind's category (``"title"``, ``"suffix"``, ``"particle"``,
#: ``"conjunction"``, ``"bound_given"``, ``"bound_second"``,
#: ``"relation"``, ``"name"``).
#: ``"relation"``, ``"name"``, ``"familiar"``, ``"spelling"``).
category: str
#: The behavioral properties as sorted ``(name, value)`` pairs,
#: spelled as the files spell them (``("addresses", "given")``), a
Expand All @@ -2006,7 +2016,7 @@ def __post_init__(self) -> None:
f"kinds are {', '.join(ri.CATEGORY)}")
if self.category != ri.CATEGORY[self.kind]:
raise ValueError(
f"a {self.kind} reading's category is "
f"{_a(self.kind)} {self.kind} reading's category is "
f"{ri.CATEGORY[self.kind]!r}, got {self.category!r}")
for name in ("properties", "languages"):
if not isinstance(getattr(self, name), tuple):
Expand Down
70 changes: 26 additions & 44 deletions nameparser/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,8 +314,9 @@ def suggest(self, names: Iterable[str]) -> Suggestion:
the base: a :class:`~nameparser.Suggestion` whose ``parser``
reads the group. ``names`` is any iterable of str the caller
declares to be one group (one source, one convention), read
once. Each name casts votes on its name order and its
patronymic shape, read with this parser's lexicon past the
once. Each name casts votes on its name order, its patronymic
shape and, where the switch is weighed (below),
``two_family_names``, read with this parser's lexicon past the
titles it lists at the head and the post-nominals at the end; a
name of fewer than two words once those are read past casts
none, and so does a name with a comma, unless only
Expand Down Expand Up @@ -409,48 +410,29 @@ def suggest(self, names: Iterable[str]) -> Suggestion:
an empty group, or one with no votes, suggests no change. A
bare str, bytes, a mapping or a non-str item raises TypeError.

Measured 2026-11-10, re-taken 2026-11-11, 2026-11-12,
2026-11-14, 2026-11-15, 2026-11-16 and 2026-11-19, with
tools/differential/suggest_measure.py on groups drawn from real
names written in a known order, 300 groups a size
(decisions/group-suggestion's 2026-11-19 #1364 and #1447
entries hold the sizes): a group written in this parser's own order kept it
in at least 97% of groups at every size from 2 to 2,000 names,
under either base order, save three lists. ORCID holders who
typed their given name in capitals (``ANNA Smith``), which the
capitals signal reads as a family name, kept their given-first
order in 52% of groups of two and 4% of five (why, in that
file's 2026-11-12 CAPITALS entry). A list of
nothing but bylines written two or three joined initials first
(``AM Hoy``) kept it in at least 97% of groups at every size
measured, to 500 names (it holds 644), but 50 and 100 names,
where it kept it in 94.7% and 93.3%, the name tables voting on
a few of its names. And a list of nothing but given names that
ORCID's holders type as surnames (``Cooper``, ``Burke``) fell
below 95% at every size and was read wrong in every group from
5 names, the surname table voting on each of them (that file's
2026-11-19 #1364 entry).
Moving the base takes more names, and
how many depends on what the names carry: groups of Chinese,
Taiwanese, Korean, Czech, Polish or Italian names (the romanized
surnames and the common given names) and of Russian ones (where
their patronymics stand) were read right in 95% of groups from 5
names; German, Dutch, Spanish, British, French,
Romanian, Vietnamese and Japanese from 10; US, Turkish,
Nigerian and Brazilian from 20; Indian from 50; and PSC's
Bangladeshi filers from 200 (PatentsView's Philippine inventors
from 20, through the Russian names among them). A group whose votes fall short of
the thresholds keeps the base rather than guess, so a smaller
group moves it in fewer of the draws. ``capitals_as_family``, measured 2026-11-12
(decisions/group-suggestion's CAPITALS entry): ORCID holders who
typed their family name in capitals were suggested it in at least
95% of groups from 4 names, and from 10 where many of the
surnames are two or three letters (holders in China, Korea,
Vietnam and Taiwan). Of the lists measured that do not write their
family names so, only ORCID holders who typed their given name in
capitals (``ANNA Smith``) were suggested it, which nothing in a
name tells apart; no other list was, ORCID's bylines (``AM Hoy``)
included. A name wholly in one case carries no evidence.
Measured on groups drawn from real names written in a known
order (:ref:`suggest-limits`; the dated tables are in the
source repository's docs/design/decisions/group-suggestion.md),
these figures give a general idea and will differ for every
dataset. A group written in this parser's own order kept it in
at least 95% of groups from 2 to 2,000 names, and in 97% for
nearly every kind, save three kinds of list: given names in
capitals (``ANNA Smith``), whose capitals read as a family name;
nothing but two or three joined initials (``AM Hoy``), which
kept it in just under 95% of groups of 50 and 93% of 100; and
nothing but given names that are common surnames elsewhere
(``Cooper``, ``Burke``), read the wrong way round. A group
written the other way round takes more names to move the base:
from 5 for Chinese, Taiwanese, Korean, Czech, Polish, Italian
and Russian names to 50 for Indian ones and 200 for Bangladeshi
ones. A group whose votes fall short of the thresholds keeps the
base rather than guess. ``capitals_as_family`` was suggested in
at least 95% of groups from 4 names for holders who typed their
family name in capitals, and from 10 where many of the surnames
are two or three letters (China, Korea, Vietnam and Taiwan); of
the lists that do not write their family names so, only the one
writing its given names in capitals was suggested it. A name
wholly in one case carries no evidence.
"""
from nameparser._suggest import suggest
return suggest(self, names)
Expand Down
26 changes: 11 additions & 15 deletions nameparser/_pipeline/_assign.py
Original file line number Diff line number Diff line change
Expand Up @@ -2060,23 +2060,19 @@ def as_a_middle(m: int, token: WorkToken) -> PendingReading:
# rules/H6: "A run of title words opening the part before a
# family comma is the title" -- by vocabulary only, never H2's
# shape, leaving one piece for the family, and stopping at a
# word that is a particle too ('St Pierre', 'Freiherr von
# Berg'), or where everything behind it is post-nominal, which
# leaves no family word to address -- H3's concern, by a
# stricter test than H3's one-word give-back, so this is not
# `leading_titles` ('VC PhD Jr., John' keeps family 'VC', where
# 'VC PhD Jr. John' reads title 'VC'). A dual is a title wherever
# a name word follows it ('Rev. Sr. Smith, Mary').
# `is_title_piece` is H5's vocabulary read, so the two slots that
# refuse the shape agree on what a title word is, save H5's
# written-short clause, which this slot does not read
# (decisions/H9, #999: 'Maj. Smith, John' keeps family 'Maj. Smith').
# word that is a particle too, or where everything behind it is
# post-nominal, which leaves no family word to address -- H3's
# concern, by a stricter test than H3's one-word give-back, so
# this is not `leading_titles`. A dual is a title wherever a name
# word follows it. `is_title_piece` is H5's vocabulary read, so
# the two slots that refuse the shape agree on what a title word
# is, save H5's written-short clause, which this slot does not
# read (decisions/H6, decisions/H9 (#999)).
#
# rules/H10: "where a title the run keeps stands behind it" --
# a dotted run ('U.S. Senator Smith, John') counts as a title
# word here as in the leading run, and one the run ends on is
# given back ('U.S. Grant Smith, John' keeps family 'U.S. Grant
# Smith'), so the roles are set once the run is known.
# a dotted run counts as a title word here as in the leading
# run, and one the run ends on is given back, so the roles are
# set once the run is known (decisions/H10 (#490)).
lead = 0
floor = len(fam_pieces)
# the length test and the tag test first, both C-level: a part
Expand Down
1 change: 1 addition & 0 deletions nameparser/_pipeline/_classify.py
Original file line number Diff line number Diff line change
Expand Up @@ -624,6 +624,7 @@ def classify(state: ParseState) -> ParseState:
# vocabulary reading, not initial-shaped) and holding a letter, and
# one written `long_names_only` too, which post_rules splits back in
# a name of fewer than four name words (decisions/P12, #1464)
#
# the marks each pair's first word takes, written in one pass after
# both walks
bound: dict[int, frozenset[str]] = {}
Expand Down
2 changes: 1 addition & 1 deletion nameparser/_pipeline/_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -2001,7 +2001,7 @@ def group(state: ParseState) -> ParseState:
# and the same reason, as _extract._overlaps and _tokenize's origin
# resolution. test_benchmark's maiden_pairs shape is the guard.
# rules/N4: "the marker dropped as M3 drops it" -- a nickname
# clause opening with an alias marker, by the same walk (#1164).
# clause opening with an alias marker, by the same walk (decisions/N4 (#1164)).
# A plain loop over a map of a C getter, no frame: a name with no
# clause pays nothing, and one with a clause no frame for the starts
starts = list(map(_SPAN_START, tokens)) if state.extracted else []
Expand Down
11 changes: 5 additions & 6 deletions nameparser/_pipeline/_post_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -806,12 +806,11 @@ def _take_second_family_name(state: ParseState, tokens: list[WorkToken],
if not any(ch.isalpha() for i in take for ch in tokens[i].text):
return
# rules/O6: "a listed given name stays where it is" -- the caller's
# Lexicon.given_names (empty by default; the es, es_ar, pt_br and
# pt_pt packs carry a list, with the switch on) names a word only a given name is, under
# either order. Only a unit of one token is asked: a word
# behind a particle ("de Miguel") is a unit of two, a surname taken
# as before. History: decisions/O6 (#959).
# A hyphenated word writing given names stays too (#959).
# Lexicon.given_names (empty by default; a pack turning O6 on may
# carry one) names a word only a given name is, under either order,
# and a hyphenated word writing given names stays too. Only a unit
# of one token is asked: a word behind a particle ("de Miguel") is a
# unit of two, a surname taken as before (decisions/O6 (#959)).
if len(take) == 1 and (
is_listed_given_name(tokens[take[0]].text, state.lexicon)
or _hyphenated_given(tokens[take[0]].text, state.lexicon)):
Expand Down
7 changes: 4 additions & 3 deletions nameparser/_policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -989,9 +989,10 @@ class Policy:
#: ``Carlos Pérez``), which is most English and Argentine names of
#: three words or more and many Portuguese and Brazilian ones as
#: filed: switched on for a mixed population it costs more names
#: than it mends, so it is off by default and reports nothing. Runs
#: before middle_as_family, which then folds whatever middles are
#: left.
#: than it mends, so it is off by default and reports nothing;
#: Parser.suggest may suggest it for a group written given name
#: first (Signal.FIRST_SURNAME). Runs before middle_as_family, which
#: then folds whatever middles are left.
two_family_names: bool = False
#: Reads the given name as two name units, for data where a person
#: carries a compound given name and no middle name (rules/O7):
Expand Down
Loading