nameparser 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- nameparser/__init__.py +7 -0
- nameparser/_version.py +2 -0
- nameparser/config/__init__.py +288 -0
- nameparser/config/capitalization.py +10 -0
- nameparser/config/conjunctions.py +15 -0
- nameparser/config/prefixes.py +47 -0
- nameparser/config/regexes.py +28 -0
- nameparser/config/suffixes.py +654 -0
- nameparser/config/titles.py +635 -0
- nameparser/parser.py +995 -0
- nameparser/py.typed +0 -0
- nameparser/util.py +17 -0
- nameparser-1.2.0.dist-info/METADATA +174 -0
- nameparser-1.2.0.dist-info/RECORD +18 -0
- nameparser-1.2.0.dist-info/WHEEL +5 -0
- nameparser-1.2.0.dist-info/licenses/AUTHORS +1 -0
- nameparser-1.2.0.dist-info/licenses/LICENSE +16 -0
- nameparser-1.2.0.dist-info/top_level.txt +1 -0
nameparser/parser.py
ADDED
|
@@ -0,0 +1,995 @@
|
|
|
1
|
+
import re
|
|
2
|
+
from collections.abc import Iterable, Iterator
|
|
3
|
+
from operator import itemgetter
|
|
4
|
+
from itertools import groupby
|
|
5
|
+
|
|
6
|
+
from typing import overload
|
|
7
|
+
|
|
8
|
+
from nameparser.util import HumanNameAttributeT, lc
|
|
9
|
+
from nameparser.util import log
|
|
10
|
+
from nameparser.config import CONSTANTS
|
|
11
|
+
from nameparser.config import Constants
|
|
12
|
+
from nameparser.config import DEFAULT_ENCODING
|
|
13
|
+
|
|
14
|
+
def group_contiguous_integers(data: Iterable[int]) -> list[tuple[int, int]]:
|
|
15
|
+
"""
|
|
16
|
+
return list of tuples containing first and last index
|
|
17
|
+
position of contiguous numbers in a series
|
|
18
|
+
"""
|
|
19
|
+
ranges: list[tuple[int, int]] = []
|
|
20
|
+
for key, group_with_indices in groupby(enumerate(data), lambda i: i[0] - i[1]):
|
|
21
|
+
group = list(map(itemgetter(1), group_with_indices))
|
|
22
|
+
if len(group) > 1:
|
|
23
|
+
ranges.append((group[0], group[-1]))
|
|
24
|
+
return ranges
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class HumanName:
|
|
28
|
+
"""
|
|
29
|
+
Parse a person's name into individual components.
|
|
30
|
+
|
|
31
|
+
Instantiation assigns to ``full_name``, and assignment to
|
|
32
|
+
:py:attr:`full_name` triggers :py:func:`parse_full_name`. After parsing the
|
|
33
|
+
name, these instance attributes are available. Alternatively, you can pass
|
|
34
|
+
any of the instance attributes to the constructor method and skip the parsing
|
|
35
|
+
process. If any of the the instance attributes are passed to the constructor
|
|
36
|
+
as keywords, :py:func:`parse_full_name` will not be performed.
|
|
37
|
+
|
|
38
|
+
**HumanName Instance Attributes**
|
|
39
|
+
|
|
40
|
+
* :py:attr:`title`
|
|
41
|
+
* :py:attr:`first`
|
|
42
|
+
* :py:attr:`middle`
|
|
43
|
+
* :py:attr:`last`
|
|
44
|
+
* :py:attr:`suffix`
|
|
45
|
+
* :py:attr:`nickname`
|
|
46
|
+
* :py:attr:`surnames`
|
|
47
|
+
|
|
48
|
+
:param str full_name: The name string to be parsed.
|
|
49
|
+
:param constants constants:
|
|
50
|
+
a :py:class:`~nameparser.config.Constants` instance. Pass ``None`` for
|
|
51
|
+
`per-instance config <customize.html>`_.
|
|
52
|
+
:param str encoding: string representing the encoding of your input
|
|
53
|
+
:param str string_format: python string formatting
|
|
54
|
+
:param str initials_format: python initials string formatting
|
|
55
|
+
:param str initials_delimter: string delimiter for initials
|
|
56
|
+
:param str first: first name
|
|
57
|
+
:param str middle: middle name
|
|
58
|
+
:param str last: last name
|
|
59
|
+
:param str title: The title or prenominal
|
|
60
|
+
:param str suffix: The suffix or postnominal
|
|
61
|
+
:param str nickname: Nicknames
|
|
62
|
+
"""
|
|
63
|
+
|
|
64
|
+
C = CONSTANTS
|
|
65
|
+
"""
|
|
66
|
+
A reference to the configuration for this instance, which may or may not be
|
|
67
|
+
a reference to the shared, module-wide instance at
|
|
68
|
+
:py:mod:`~nameparser.config.CONSTANTS`. See `Customizing the Parser
|
|
69
|
+
<customize.html>`_.
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
original: str | bytes = ''
|
|
73
|
+
"""
|
|
74
|
+
The original string, untouched by the parser.
|
|
75
|
+
"""
|
|
76
|
+
|
|
77
|
+
_count = 0
|
|
78
|
+
_members = ['title', 'first', 'middle', 'last', 'suffix', 'nickname']
|
|
79
|
+
unparsable = True
|
|
80
|
+
_full_name = ''
|
|
81
|
+
|
|
82
|
+
title_list: list[str]
|
|
83
|
+
first_list: list[str]
|
|
84
|
+
middle_list: list[str]
|
|
85
|
+
last_list: list[str]
|
|
86
|
+
suffix_list: list[str]
|
|
87
|
+
nickname_list: list[str]
|
|
88
|
+
|
|
89
|
+
def __init__(
|
|
90
|
+
self,
|
|
91
|
+
full_name: str | bytes = "",
|
|
92
|
+
constants: Constants = CONSTANTS,
|
|
93
|
+
encoding: str = DEFAULT_ENCODING,
|
|
94
|
+
string_format: str | None = None,
|
|
95
|
+
initials_format: str | None = None,
|
|
96
|
+
initials_delimiter: str | None = None,
|
|
97
|
+
first: str | list[str] | None = None,
|
|
98
|
+
middle: str | list[str] | None = None,
|
|
99
|
+
last: str | list[str] | None = None,
|
|
100
|
+
title: str | list[str] | None = None,
|
|
101
|
+
suffix: str | list[str] | None = None,
|
|
102
|
+
nickname: str | list[str] | None = None,
|
|
103
|
+
) -> None:
|
|
104
|
+
self.C = constants
|
|
105
|
+
if type(self.C) is not type(CONSTANTS):
|
|
106
|
+
self.C = Constants()
|
|
107
|
+
|
|
108
|
+
self.encoding = encoding
|
|
109
|
+
self.string_format = string_format or self.C.string_format
|
|
110
|
+
self.initials_format = initials_format or self.C.initials_format
|
|
111
|
+
self.initials_delimiter = initials_delimiter or self.C.initials_delimiter
|
|
112
|
+
if (first or middle or last or title or suffix or nickname):
|
|
113
|
+
self.first = first
|
|
114
|
+
self.middle = middle
|
|
115
|
+
self.last = last
|
|
116
|
+
self.title = title
|
|
117
|
+
self.suffix = suffix
|
|
118
|
+
self.nickname = nickname
|
|
119
|
+
self.unparsable = False
|
|
120
|
+
else:
|
|
121
|
+
# full_name setter triggers the parse
|
|
122
|
+
self.full_name = full_name
|
|
123
|
+
|
|
124
|
+
def __iter__(self) -> Iterator[str]:
|
|
125
|
+
return self
|
|
126
|
+
|
|
127
|
+
def __len__(self) -> int:
|
|
128
|
+
l = 0
|
|
129
|
+
for x in self:
|
|
130
|
+
l += 1
|
|
131
|
+
return l
|
|
132
|
+
|
|
133
|
+
def __eq__(self, other: object) -> bool:
|
|
134
|
+
"""
|
|
135
|
+
HumanName instances are equal to other objects whose
|
|
136
|
+
lower case unicode representation is the same.
|
|
137
|
+
"""
|
|
138
|
+
return str(self).lower() == str(other).lower()
|
|
139
|
+
|
|
140
|
+
def __ne__(self, other: object) -> bool:
|
|
141
|
+
return not str(self).lower() == str(other).lower()
|
|
142
|
+
|
|
143
|
+
@overload
|
|
144
|
+
def __getitem__(self, key: slice) -> list[str]: ...
|
|
145
|
+
@overload
|
|
146
|
+
def __getitem__(self, key: str) -> str: ...
|
|
147
|
+
def __getitem__(self, key: slice | str) -> str | list[str]:
|
|
148
|
+
if isinstance(key, slice):
|
|
149
|
+
return [getattr(self, x) for x in self._members[key]]
|
|
150
|
+
else:
|
|
151
|
+
return getattr(self, key)
|
|
152
|
+
|
|
153
|
+
def __setitem__(self, key: str, value: str) -> None:
|
|
154
|
+
if key in self._members:
|
|
155
|
+
self._set_list(key, value)
|
|
156
|
+
else:
|
|
157
|
+
raise KeyError("Not a valid HumanName attribute", key)
|
|
158
|
+
|
|
159
|
+
def __next__(self) -> str:
|
|
160
|
+
if self._count >= len(self._members):
|
|
161
|
+
self._count = 0
|
|
162
|
+
raise StopIteration
|
|
163
|
+
else:
|
|
164
|
+
c = self._count
|
|
165
|
+
self._count = c + 1
|
|
166
|
+
return getattr(self, self._members[c]) or next(self)
|
|
167
|
+
|
|
168
|
+
def __str__(self) -> str:
|
|
169
|
+
if self.string_format:
|
|
170
|
+
# string_format = "{title} {first} {middle} {last} {suffix} ({nickname})"
|
|
171
|
+
_s = self.string_format.format(**self.as_dict())
|
|
172
|
+
# remove trailing punctuation from missing nicknames
|
|
173
|
+
_s = _s.replace(str(self.C.empty_attribute_default), '').replace(" ()", "").replace(" ''", "").replace(' ""', "")
|
|
174
|
+
return self.collapse_whitespace(_s).strip(', ')
|
|
175
|
+
return " ".join(self)
|
|
176
|
+
|
|
177
|
+
def __hash__(self) -> int:
|
|
178
|
+
return hash(str(self))
|
|
179
|
+
|
|
180
|
+
def __repr__(self) -> str:
|
|
181
|
+
if self.unparsable:
|
|
182
|
+
_string = "<%(class)s : [ Unparsable ] >" % {'class': self.__class__.__name__, }
|
|
183
|
+
else:
|
|
184
|
+
_string = "<%(class)s : [\n\ttitle: %(title)r \n\tfirst: %(first)r \n\tmiddle: %(middle)r \n\tlast: %(last)r \n\tsuffix: %(suffix)r\n\tnickname: %(nickname)r\n]>" % {
|
|
185
|
+
'class': self.__class__.__name__,
|
|
186
|
+
'title': self.title or '',
|
|
187
|
+
'first': self.first or '',
|
|
188
|
+
'middle': self.middle or '',
|
|
189
|
+
'last': self.last or '',
|
|
190
|
+
'suffix': self.suffix or '',
|
|
191
|
+
'nickname': self.nickname or '',
|
|
192
|
+
}
|
|
193
|
+
return _string
|
|
194
|
+
|
|
195
|
+
def as_dict(self, include_empty: bool = True) -> dict[str, str]:
|
|
196
|
+
"""
|
|
197
|
+
Return the parsed name as a dictionary of its attributes.
|
|
198
|
+
|
|
199
|
+
:param bool include_empty: Include keys in the dictionary for empty name attributes.
|
|
200
|
+
:rtype: dict
|
|
201
|
+
|
|
202
|
+
.. doctest::
|
|
203
|
+
|
|
204
|
+
>>> name = HumanName("Bob Dole")
|
|
205
|
+
>>> name.as_dict()
|
|
206
|
+
{'last': 'Dole', 'suffix': '', 'title': '', 'middle': '', 'nickname': '', 'first': 'Bob'}
|
|
207
|
+
>>> name.as_dict(False)
|
|
208
|
+
{'last': 'Dole', 'first': 'Bob'}
|
|
209
|
+
|
|
210
|
+
"""
|
|
211
|
+
d = {}
|
|
212
|
+
for m in self._members:
|
|
213
|
+
if include_empty:
|
|
214
|
+
d[m] = getattr(self, m)
|
|
215
|
+
else:
|
|
216
|
+
val = getattr(self, m)
|
|
217
|
+
if val:
|
|
218
|
+
d[m] = val
|
|
219
|
+
return d
|
|
220
|
+
|
|
221
|
+
def __process_initial__(self, name_part: str, firstname: bool = False) -> str:
|
|
222
|
+
"""
|
|
223
|
+
Name parts may include prefixes or conjunctions. This function filters these from the name unless it is
|
|
224
|
+
a first name, since first names cannot be conjunctions or prefixes.
|
|
225
|
+
"""
|
|
226
|
+
parts = name_part.split(" ")
|
|
227
|
+
initials = []
|
|
228
|
+
if len(parts) and isinstance(parts, list):
|
|
229
|
+
for part in parts:
|
|
230
|
+
if not (self.is_prefix(part) or self.is_conjunction(part)) or firstname:
|
|
231
|
+
initials.append(part[0])
|
|
232
|
+
if len(initials) > 0:
|
|
233
|
+
return " ".join(initials)
|
|
234
|
+
else:
|
|
235
|
+
return self.C.empty_attribute_default
|
|
236
|
+
|
|
237
|
+
def initials_list(self) -> list[str]:
|
|
238
|
+
"""
|
|
239
|
+
Returns the initials as a list
|
|
240
|
+
|
|
241
|
+
.. doctest::
|
|
242
|
+
|
|
243
|
+
>>> name = HumanName("Sir Bob Andrew Dole")
|
|
244
|
+
>>> name.initials_list()
|
|
245
|
+
["B", "A", "D"]
|
|
246
|
+
>>> name = HumanName("J. Doe")
|
|
247
|
+
>>> name.initials_list()
|
|
248
|
+
["J", "D"]
|
|
249
|
+
"""
|
|
250
|
+
first_initials_list = [self.__process_initial__(name, True) for name in self.first_list if name]
|
|
251
|
+
middle_initials_list = [self.__process_initial__(name) for name in self.middle_list if name]
|
|
252
|
+
last_initials_list = [self.__process_initial__(name) for name in self.last_list if name]
|
|
253
|
+
return first_initials_list + middle_initials_list + last_initials_list
|
|
254
|
+
|
|
255
|
+
def initials(self) -> str:
|
|
256
|
+
"""
|
|
257
|
+
Return period-delimited initials of the first, middle and optionally last name.
|
|
258
|
+
|
|
259
|
+
:param bool include_last_name: Include the last name as part of the initials
|
|
260
|
+
:rtype: str
|
|
261
|
+
|
|
262
|
+
.. doctest::
|
|
263
|
+
|
|
264
|
+
>>> name = HumanName("Sir Bob Andrew Dole")
|
|
265
|
+
>>> name.initials()
|
|
266
|
+
"B. A. D."
|
|
267
|
+
>>> name = HumanName("Sir Bob Andrew Dole", initials_format="{first} {middle}")
|
|
268
|
+
>>> name.initials()
|
|
269
|
+
"B. A."
|
|
270
|
+
"""
|
|
271
|
+
|
|
272
|
+
first_initials_list = [self.__process_initial__(name, True) for name in self.first_list if name]
|
|
273
|
+
middle_initials_list = [self.__process_initial__(name) for name in self.middle_list if name]
|
|
274
|
+
last_initials_list = [self.__process_initial__(name) for name in self.last_list if name]
|
|
275
|
+
|
|
276
|
+
initials_dict = {
|
|
277
|
+
"first": (self.initials_delimiter + " ").join(first_initials_list) + self.initials_delimiter
|
|
278
|
+
if len(first_initials_list) else self.C.empty_attribute_default,
|
|
279
|
+
"middle": (self.initials_delimiter + " ").join(middle_initials_list) + self.initials_delimiter
|
|
280
|
+
if len(middle_initials_list) else self.C.empty_attribute_default,
|
|
281
|
+
"last": (self.initials_delimiter + " ").join(last_initials_list) + self.initials_delimiter
|
|
282
|
+
if len(last_initials_list) else self.C.empty_attribute_default
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
_s = self.initials_format.format(**initials_dict)
|
|
286
|
+
return self.collapse_whitespace(_s)
|
|
287
|
+
|
|
288
|
+
@property
|
|
289
|
+
def has_own_config(self) -> bool:
|
|
290
|
+
"""
|
|
291
|
+
True if this instance is not using the shared module-level
|
|
292
|
+
configuration.
|
|
293
|
+
"""
|
|
294
|
+
return self.C is not CONSTANTS
|
|
295
|
+
|
|
296
|
+
# attributes
|
|
297
|
+
|
|
298
|
+
@property
|
|
299
|
+
def title(self) -> str:
|
|
300
|
+
"""
|
|
301
|
+
The person's titles. Any string of consecutive pieces in
|
|
302
|
+
:py:mod:`~nameparser.config.titles` or
|
|
303
|
+
:py:mod:`~nameparser.config.conjunctions`
|
|
304
|
+
at the beginning of :py:attr:`full_name`.
|
|
305
|
+
"""
|
|
306
|
+
return " ".join(self.title_list) or self.C.empty_attribute_default
|
|
307
|
+
|
|
308
|
+
@title.setter
|
|
309
|
+
def title(self, value: str | list[str] | None) -> None:
|
|
310
|
+
self._set_list('title', value)
|
|
311
|
+
|
|
312
|
+
@property
|
|
313
|
+
def first(self) -> str:
|
|
314
|
+
"""
|
|
315
|
+
The person's first name. The first name piece after any known
|
|
316
|
+
:py:attr:`title` pieces parsed from :py:attr:`full_name`.
|
|
317
|
+
"""
|
|
318
|
+
return " ".join(self.first_list) or self.C.empty_attribute_default
|
|
319
|
+
|
|
320
|
+
@first.setter
|
|
321
|
+
def first(self, value: str | list[str] | None) -> None:
|
|
322
|
+
self._set_list('first', value)
|
|
323
|
+
|
|
324
|
+
@property
|
|
325
|
+
def middle(self) -> str:
|
|
326
|
+
"""
|
|
327
|
+
The person's middle names. All name pieces after the first name and
|
|
328
|
+
before the last name parsed from :py:attr:`full_name`.
|
|
329
|
+
"""
|
|
330
|
+
return " ".join(self.middle_list) or self.C.empty_attribute_default
|
|
331
|
+
|
|
332
|
+
@middle.setter
|
|
333
|
+
def middle(self, value: str | list[str] | None) -> None:
|
|
334
|
+
self._set_list('middle', value)
|
|
335
|
+
|
|
336
|
+
@property
|
|
337
|
+
def last(self) -> str:
|
|
338
|
+
"""
|
|
339
|
+
The person's last name. The last name piece parsed from
|
|
340
|
+
:py:attr:`full_name`.
|
|
341
|
+
"""
|
|
342
|
+
return " ".join(self.last_list) or self.C.empty_attribute_default
|
|
343
|
+
|
|
344
|
+
@last.setter
|
|
345
|
+
def last(self, value: str | list[str] | None) -> None:
|
|
346
|
+
self._set_list('last', value)
|
|
347
|
+
|
|
348
|
+
@property
|
|
349
|
+
def suffix(self) -> str:
|
|
350
|
+
"""
|
|
351
|
+
The persons's suffixes. Pieces at the end of the name that are found in
|
|
352
|
+
:py:mod:`~nameparser.config.suffixes`, or pieces that are at the end
|
|
353
|
+
of comma separated formats, e.g.
|
|
354
|
+
"Lastname, Title Firstname Middle[,] Suffix [, Suffix]" parsed
|
|
355
|
+
from :py:attr:`full_name`.
|
|
356
|
+
"""
|
|
357
|
+
return ", ".join(self.suffix_list) or self.C.empty_attribute_default
|
|
358
|
+
|
|
359
|
+
@suffix.setter
|
|
360
|
+
def suffix(self, value: str | list[str] | None) -> None:
|
|
361
|
+
self._set_list('suffix', value)
|
|
362
|
+
|
|
363
|
+
@property
|
|
364
|
+
def nickname(self) -> str:
|
|
365
|
+
"""
|
|
366
|
+
The person's nicknames. Any text found inside of quotes (``""``) or
|
|
367
|
+
parenthesis (``()``)
|
|
368
|
+
"""
|
|
369
|
+
return " ".join(self.nickname_list) or self.C.empty_attribute_default
|
|
370
|
+
|
|
371
|
+
@nickname.setter
|
|
372
|
+
def nickname(self, value: str | list[str] | None) -> None:
|
|
373
|
+
self._set_list('nickname', value)
|
|
374
|
+
|
|
375
|
+
@property
|
|
376
|
+
def surnames_list(self) -> list[str]:
|
|
377
|
+
"""
|
|
378
|
+
List of middle names followed by last name.
|
|
379
|
+
"""
|
|
380
|
+
return self.middle_list + self.last_list
|
|
381
|
+
|
|
382
|
+
@property
|
|
383
|
+
def surnames(self) -> str:
|
|
384
|
+
"""
|
|
385
|
+
A string of all middle names followed by the last name.
|
|
386
|
+
"""
|
|
387
|
+
return " ".join(self.surnames_list) or self.C.empty_attribute_default
|
|
388
|
+
|
|
389
|
+
# setter methods
|
|
390
|
+
|
|
391
|
+
def _set_list(self, attr: str, value: str | list[str] | None) -> None:
|
|
392
|
+
if isinstance(value, list):
|
|
393
|
+
val = value
|
|
394
|
+
elif isinstance(value, (str, bytes)):
|
|
395
|
+
val = [value]
|
|
396
|
+
elif value is None:
|
|
397
|
+
val = []
|
|
398
|
+
else:
|
|
399
|
+
raise TypeError(
|
|
400
|
+
"Can only assign strings, lists or None to name attributes."
|
|
401
|
+
" Got {}".format(type(value)))
|
|
402
|
+
setattr(self, attr+"_list", self.parse_pieces(val))
|
|
403
|
+
|
|
404
|
+
# Parse helpers
|
|
405
|
+
def is_title(self, value: str) -> bool:
|
|
406
|
+
"""Is in the :py:data:`~nameparser.config.titles.TITLES` set."""
|
|
407
|
+
return lc(value) in self.C.titles
|
|
408
|
+
|
|
409
|
+
def is_conjunction(self, piece: str) -> bool:
|
|
410
|
+
"""Is in the conjunctions set and not :py:func:`is_an_initial()`."""
|
|
411
|
+
if isinstance(piece, list):
|
|
412
|
+
for item in piece:
|
|
413
|
+
if self.is_conjunction(item):
|
|
414
|
+
return True
|
|
415
|
+
else:
|
|
416
|
+
return piece.lower() in self.C.conjunctions and not self.is_an_initial(piece)
|
|
417
|
+
|
|
418
|
+
def is_prefix(self, piece: str) -> bool:
|
|
419
|
+
"""
|
|
420
|
+
Lowercase and no periods version of piece is in the
|
|
421
|
+
:py:data:`~nameparser.config.prefixes.PREFIXES` set.
|
|
422
|
+
"""
|
|
423
|
+
if isinstance(piece, list):
|
|
424
|
+
for item in piece:
|
|
425
|
+
if self.is_prefix(item):
|
|
426
|
+
return True
|
|
427
|
+
else:
|
|
428
|
+
return lc(piece) in self.C.prefixes
|
|
429
|
+
|
|
430
|
+
def is_roman_numeral(self, value: str) -> bool:
|
|
431
|
+
"""
|
|
432
|
+
Matches the ``roman_numeral`` regular expression in
|
|
433
|
+
:py:data:`~nameparser.config.regexes.REGEXES`.
|
|
434
|
+
"""
|
|
435
|
+
return bool(self.C.regexes.roman_numeral.match(value))
|
|
436
|
+
|
|
437
|
+
def is_suffix(self, piece: str) -> bool:
|
|
438
|
+
"""
|
|
439
|
+
Is in the suffixes set and not :py:func:`is_an_initial()`.
|
|
440
|
+
|
|
441
|
+
Some suffixes may be acronyms (M.B.A) while some are not (Jr.),
|
|
442
|
+
so we remove the periods from `piece` when testing against
|
|
443
|
+
`C.suffix_acronyms`.
|
|
444
|
+
"""
|
|
445
|
+
# suffixes may have periods inside them like "M.D."
|
|
446
|
+
if isinstance(piece, list):
|
|
447
|
+
for item in piece:
|
|
448
|
+
if self.is_suffix(item):
|
|
449
|
+
return True
|
|
450
|
+
else:
|
|
451
|
+
return ((lc(piece).replace('.', '') in self.C.suffix_acronyms)
|
|
452
|
+
or (lc(piece) in self.C.suffix_not_acronyms)) \
|
|
453
|
+
and not self.is_an_initial(piece)
|
|
454
|
+
|
|
455
|
+
def are_suffixes(self, pieces: Iterable[str]) -> bool:
|
|
456
|
+
"""Return True if all pieces are suffixes."""
|
|
457
|
+
for piece in pieces:
|
|
458
|
+
if not self.is_suffix(piece):
|
|
459
|
+
return False
|
|
460
|
+
return True
|
|
461
|
+
|
|
462
|
+
def is_rootname(self, piece: str) -> bool:
|
|
463
|
+
"""
|
|
464
|
+
Is not a known title, suffix or prefix. Just first, middle, last names.
|
|
465
|
+
"""
|
|
466
|
+
return lc(piece) not in self.C.suffixes_prefixes_titles \
|
|
467
|
+
and not self.is_an_initial(piece)
|
|
468
|
+
|
|
469
|
+
def is_an_initial(self, value: str) -> bool:
|
|
470
|
+
"""
|
|
471
|
+
Words with a single period at the end, or a single uppercase letter.
|
|
472
|
+
|
|
473
|
+
Matches the ``initial`` regular expression in
|
|
474
|
+
:py:data:`~nameparser.config.regexes.REGEXES`.
|
|
475
|
+
"""
|
|
476
|
+
return bool(self.C.regexes.initial.match(value))
|
|
477
|
+
|
|
478
|
+
# full_name parser
|
|
479
|
+
|
|
480
|
+
@property
|
|
481
|
+
def full_name(self) -> str:
|
|
482
|
+
"""The string output of the HumanName instance."""
|
|
483
|
+
return self.__str__()
|
|
484
|
+
|
|
485
|
+
@full_name.setter
|
|
486
|
+
def full_name(self, value: str | bytes) -> None:
|
|
487
|
+
self.original = value
|
|
488
|
+
|
|
489
|
+
if isinstance(value, bytes):
|
|
490
|
+
self._full_name = value.decode(self.encoding)
|
|
491
|
+
else:
|
|
492
|
+
self._full_name = value
|
|
493
|
+
|
|
494
|
+
self.parse_full_name()
|
|
495
|
+
|
|
496
|
+
def collapse_whitespace(self, string: str) -> str:
|
|
497
|
+
# collapse multiple spaces into single space
|
|
498
|
+
string = self.C.regexes.spaces.sub(" ", string.strip())
|
|
499
|
+
if string.endswith(","):
|
|
500
|
+
string = string[:-1]
|
|
501
|
+
return string
|
|
502
|
+
|
|
503
|
+
def pre_process(self) -> None:
|
|
504
|
+
"""
|
|
505
|
+
|
|
506
|
+
This method happens at the beginning of the :py:func:`parse_full_name`
|
|
507
|
+
before any other processing of the string aside from unicode
|
|
508
|
+
normalization, so it's a good place to do any custom handling in a
|
|
509
|
+
subclass. Runs :py:func:`parse_nicknames` and :py:func:`squash_emoji`.
|
|
510
|
+
|
|
511
|
+
"""
|
|
512
|
+
self.fix_phd()
|
|
513
|
+
self.parse_nicknames()
|
|
514
|
+
self.squash_emoji()
|
|
515
|
+
|
|
516
|
+
def post_process(self) -> None:
|
|
517
|
+
"""
|
|
518
|
+
This happens at the end of the :py:func:`parse_full_name` after
|
|
519
|
+
all other processing has taken place. Runs :py:func:`handle_firstnames`
|
|
520
|
+
and :py:func:`handle_capitalization`.
|
|
521
|
+
"""
|
|
522
|
+
self.handle_firstnames()
|
|
523
|
+
self.handle_capitalization()
|
|
524
|
+
|
|
525
|
+
def fix_phd(self) -> None:
|
|
526
|
+
_re = self.C.regexes.phd
|
|
527
|
+
|
|
528
|
+
if match := _re.search(self._full_name):
|
|
529
|
+
self.suffix_list.extend(match.groups())
|
|
530
|
+
self._full_name = _re.sub('', self._full_name)
|
|
531
|
+
|
|
532
|
+
def parse_nicknames(self) -> None:
|
|
533
|
+
"""
|
|
534
|
+
The content of parenthesis or quotes in the name will be added to the
|
|
535
|
+
nicknames list. This happens before any other processing of the name.
|
|
536
|
+
|
|
537
|
+
Single quotes cannot span white space characters and must border
|
|
538
|
+
white space to allow for quotes in names like O'Connor and Kawai'ae'a.
|
|
539
|
+
Double quotes and parenthesis can span white space.
|
|
540
|
+
|
|
541
|
+
Loops through 3 :py:data:`~nameparser.config.regexes.REGEXES`;
|
|
542
|
+
`quoted_word`, `double_quotes` and `parenthesis`.
|
|
543
|
+
"""
|
|
544
|
+
|
|
545
|
+
re_quoted_word = self.C.regexes.quoted_word
|
|
546
|
+
re_double_quotes = self.C.regexes.double_quotes
|
|
547
|
+
re_parenthesis = self.C.regexes.parenthesis
|
|
548
|
+
|
|
549
|
+
for _re in (re_quoted_word, re_double_quotes, re_parenthesis):
|
|
550
|
+
if _re.search(self._full_name):
|
|
551
|
+
self.nickname_list += [x for x in _re.findall(self._full_name)]
|
|
552
|
+
self._full_name = _re.sub('', self._full_name)
|
|
553
|
+
|
|
554
|
+
def squash_emoji(self) -> None:
|
|
555
|
+
"""
|
|
556
|
+
Remove emoji from the input string.
|
|
557
|
+
"""
|
|
558
|
+
re_emoji = self.C.regexes.emoji
|
|
559
|
+
if re_emoji and re_emoji.search(self._full_name):
|
|
560
|
+
self._full_name = re_emoji.sub('', self._full_name)
|
|
561
|
+
|
|
562
|
+
def handle_firstnames(self) -> None:
|
|
563
|
+
"""
|
|
564
|
+
If there are only two parts and one is a title, assume it's a last name
|
|
565
|
+
instead of a first name. e.g. Mr. Johnson. Unless it's a special title
|
|
566
|
+
like "Sir", then when it's followed by a single name that name is always
|
|
567
|
+
a first name.
|
|
568
|
+
"""
|
|
569
|
+
if self.title \
|
|
570
|
+
and len(self) == 2 \
|
|
571
|
+
and lc(self.title) not in self.C.first_name_titles:
|
|
572
|
+
self.last, self.first = self.first, self.last
|
|
573
|
+
|
|
574
|
+
def parse_full_name(self) -> None:
|
|
575
|
+
"""
|
|
576
|
+
|
|
577
|
+
The main parse method for the parser. This method is run upon
|
|
578
|
+
assignment to the :py:attr:`full_name` attribute or instantiation.
|
|
579
|
+
|
|
580
|
+
Basic flow is to hand off to :py:func:`pre_process` to handle
|
|
581
|
+
nicknames. It then splits on commas and chooses a code path depending
|
|
582
|
+
on the number of commas.
|
|
583
|
+
|
|
584
|
+
:py:func:`parse_pieces` then splits those parts on spaces and
|
|
585
|
+
:py:func:`join_on_conjunctions` joins any pieces next to conjunctions.
|
|
586
|
+
"""
|
|
587
|
+
|
|
588
|
+
self.title_list = []
|
|
589
|
+
self.first_list = []
|
|
590
|
+
self.middle_list = []
|
|
591
|
+
self.last_list = []
|
|
592
|
+
self.suffix_list = []
|
|
593
|
+
self.nickname_list = []
|
|
594
|
+
self.unparsable = True
|
|
595
|
+
|
|
596
|
+
self.pre_process()
|
|
597
|
+
|
|
598
|
+
self._full_name = self.collapse_whitespace(self._full_name)
|
|
599
|
+
|
|
600
|
+
# break up full_name by commas
|
|
601
|
+
parts = [x.strip() for x in self._full_name.split(",")]
|
|
602
|
+
|
|
603
|
+
log.debug("full_name: %s", self._full_name)
|
|
604
|
+
log.debug("parts: %s", parts)
|
|
605
|
+
|
|
606
|
+
if len(parts) == 1:
|
|
607
|
+
|
|
608
|
+
# no commas, title first middle middle middle last suffix
|
|
609
|
+
# part[0]
|
|
610
|
+
|
|
611
|
+
pieces = self.parse_pieces(parts)
|
|
612
|
+
p_len = len(pieces)
|
|
613
|
+
for i, piece in enumerate(pieces):
|
|
614
|
+
try:
|
|
615
|
+
nxt = pieces[i + 1]
|
|
616
|
+
except IndexError:
|
|
617
|
+
nxt = None
|
|
618
|
+
|
|
619
|
+
# title must have a next piece, unless it's just a title
|
|
620
|
+
if not self.first \
|
|
621
|
+
and (nxt or p_len == 1) \
|
|
622
|
+
and self.is_title(piece):
|
|
623
|
+
self.title_list.append(piece)
|
|
624
|
+
continue
|
|
625
|
+
if not self.first:
|
|
626
|
+
if p_len == 1 and self.nickname:
|
|
627
|
+
self.last_list.append(piece)
|
|
628
|
+
continue
|
|
629
|
+
self.first_list.append(piece)
|
|
630
|
+
continue
|
|
631
|
+
if self.are_suffixes(pieces[i+1:]) or \
|
|
632
|
+
(
|
|
633
|
+
# if the next piece is the last piece and a roman
|
|
634
|
+
# numeral but this piece is not an initial
|
|
635
|
+
nxt is not None and \
|
|
636
|
+
self.is_roman_numeral(nxt) and i == p_len - 2
|
|
637
|
+
and not self.is_an_initial(piece)
|
|
638
|
+
):
|
|
639
|
+
self.last_list.append(piece)
|
|
640
|
+
self.suffix_list += pieces[i+1:]
|
|
641
|
+
break
|
|
642
|
+
if not nxt:
|
|
643
|
+
self.last_list.append(piece)
|
|
644
|
+
continue
|
|
645
|
+
|
|
646
|
+
self.middle_list.append(piece)
|
|
647
|
+
else:
|
|
648
|
+
# if all the end parts are suffixes and there is more than one piece
|
|
649
|
+
# in the first part. (Suffixes will never appear after last names
|
|
650
|
+
# only, and allows potential first names to be in suffixes, e.g.
|
|
651
|
+
# "Johnson, Bart"
|
|
652
|
+
|
|
653
|
+
post_comma_pieces = self.parse_pieces(parts[1].split(' '), 1)
|
|
654
|
+
|
|
655
|
+
if self.are_suffixes(parts[1].split(' ')) \
|
|
656
|
+
and len(parts[0].split(' ')) > 1:
|
|
657
|
+
|
|
658
|
+
# suffix comma:
|
|
659
|
+
# title first middle last [suffix], suffix [suffix] [, suffix]
|
|
660
|
+
# parts[0], parts[1:...]
|
|
661
|
+
|
|
662
|
+
self.suffix_list += parts[1:]
|
|
663
|
+
pieces = self.parse_pieces(parts[0].split(' '))
|
|
664
|
+
log.debug("pieces: %s", str(pieces))
|
|
665
|
+
for i, piece in enumerate(pieces):
|
|
666
|
+
try:
|
|
667
|
+
nxt = pieces[i + 1]
|
|
668
|
+
except IndexError:
|
|
669
|
+
nxt = None
|
|
670
|
+
|
|
671
|
+
if not self.first \
|
|
672
|
+
and (nxt or len(pieces) == 1) \
|
|
673
|
+
and self.is_title(piece):
|
|
674
|
+
self.title_list.append(piece)
|
|
675
|
+
continue
|
|
676
|
+
if not self.first:
|
|
677
|
+
self.first_list.append(piece)
|
|
678
|
+
continue
|
|
679
|
+
if self.are_suffixes(pieces[i+1:]):
|
|
680
|
+
self.last_list.append(piece)
|
|
681
|
+
self.suffix_list = pieces[i+1:] + self.suffix_list
|
|
682
|
+
break
|
|
683
|
+
if not nxt:
|
|
684
|
+
self.last_list.append(piece)
|
|
685
|
+
continue
|
|
686
|
+
self.middle_list.append(piece)
|
|
687
|
+
else:
|
|
688
|
+
|
|
689
|
+
# lastname comma:
|
|
690
|
+
# last [suffix], title first middles[,] suffix [,suffix]
|
|
691
|
+
# parts[0], parts[1], parts[2:...]
|
|
692
|
+
|
|
693
|
+
log.debug("post-comma pieces: %s", str(post_comma_pieces))
|
|
694
|
+
|
|
695
|
+
# lastname part may have suffixes in it
|
|
696
|
+
lastname_pieces = self.parse_pieces(parts[0].split(' '), 1)
|
|
697
|
+
for piece in lastname_pieces:
|
|
698
|
+
# the first one is always a last name, even if it looks like
|
|
699
|
+
# a suffix
|
|
700
|
+
if self.is_suffix(piece) and len(self.last_list) > 0:
|
|
701
|
+
self.suffix_list.append(piece)
|
|
702
|
+
else:
|
|
703
|
+
self.last_list.append(piece)
|
|
704
|
+
|
|
705
|
+
for i, piece in enumerate(post_comma_pieces):
|
|
706
|
+
try:
|
|
707
|
+
nxt = post_comma_pieces[i + 1]
|
|
708
|
+
except IndexError:
|
|
709
|
+
nxt = None
|
|
710
|
+
|
|
711
|
+
if not self.first \
|
|
712
|
+
and (nxt or len(post_comma_pieces) == 1) \
|
|
713
|
+
and self.is_title(piece):
|
|
714
|
+
self.title_list.append(piece)
|
|
715
|
+
continue
|
|
716
|
+
if not self.first:
|
|
717
|
+
self.first_list.append(piece)
|
|
718
|
+
continue
|
|
719
|
+
if self.is_suffix(piece):
|
|
720
|
+
self.suffix_list.append(piece)
|
|
721
|
+
continue
|
|
722
|
+
self.middle_list.append(piece)
|
|
723
|
+
try:
|
|
724
|
+
if parts[2]:
|
|
725
|
+
self.suffix_list += parts[2:]
|
|
726
|
+
except IndexError:
|
|
727
|
+
pass
|
|
728
|
+
|
|
729
|
+
if len(self) < 0:
|
|
730
|
+
log.info("Unparsable: \"%s\" ", self.original)
|
|
731
|
+
else:
|
|
732
|
+
self.unparsable = False
|
|
733
|
+
self.post_process()
|
|
734
|
+
|
|
735
|
+
def parse_pieces(self, parts: Iterable[str], additional_parts_count: int = 0) -> list[str]:
|
|
736
|
+
"""
|
|
737
|
+
Split parts on spaces and remove commas, join on conjunctions and
|
|
738
|
+
lastname prefixes. If parts have periods in the middle, try splitting
|
|
739
|
+
on periods and check if the parts are titles or suffixes. If they are
|
|
740
|
+
add to the constant so they will be found.
|
|
741
|
+
|
|
742
|
+
:param list parts: name part strings from the comma split
|
|
743
|
+
:param int additional_parts_count:
|
|
744
|
+
|
|
745
|
+
if the comma format contains other parts, we need to know
|
|
746
|
+
how many there are to decide if things should be considered a
|
|
747
|
+
conjunction.
|
|
748
|
+
:return: pieces split on spaces and joined on conjunctions
|
|
749
|
+
:rtype: list
|
|
750
|
+
"""
|
|
751
|
+
|
|
752
|
+
output: list[str] = []
|
|
753
|
+
for part in parts:
|
|
754
|
+
if not isinstance(part, (str, bytes)):
|
|
755
|
+
raise TypeError("Name parts must be strings. "
|
|
756
|
+
" Got {}".format(type(part)))
|
|
757
|
+
output += [x.strip(' ,') for x in part.split(' ')]
|
|
758
|
+
|
|
759
|
+
# If part contains periods, check if it's multiple titles or suffixes
|
|
760
|
+
# together without spaces if so, add the new part with periods to the
|
|
761
|
+
# constants so they get parsed correctly later
|
|
762
|
+
for part in output:
|
|
763
|
+
# if this part has a period not at the beginning or end
|
|
764
|
+
if self.C.regexes.period_not_at_end and self.C.regexes.period_not_at_end.match(part):
|
|
765
|
+
# split on periods, any of the split pieces titles or suffixes?
|
|
766
|
+
# ("Lt.Gov.")
|
|
767
|
+
period_chunks = part.split(".")
|
|
768
|
+
titles = list(filter(self.is_title, period_chunks))
|
|
769
|
+
suffixes = list(filter(self.is_suffix, period_chunks))
|
|
770
|
+
|
|
771
|
+
# add the part to the constant so it will be found
|
|
772
|
+
if len(list(titles)):
|
|
773
|
+
self.C.titles.add(part)
|
|
774
|
+
continue
|
|
775
|
+
if len(list(suffixes)):
|
|
776
|
+
self.C.suffix_not_acronyms.add(part)
|
|
777
|
+
continue
|
|
778
|
+
|
|
779
|
+
return self.join_on_conjunctions(output, additional_parts_count)
|
|
780
|
+
|
|
781
|
+
def join_on_conjunctions(self, pieces: list[str], additional_parts_count: int = 0) -> list[str]:
|
|
782
|
+
"""
|
|
783
|
+
Join conjunctions to surrounding pieces. Title- and prefix-aware. e.g.:
|
|
784
|
+
|
|
785
|
+
['Mr.', 'and'. 'Mrs.', 'John', 'Doe'] ==>
|
|
786
|
+
['Mr. and Mrs.', 'John', 'Doe']
|
|
787
|
+
|
|
788
|
+
['The', 'Secretary', 'of', 'State', 'Hillary', 'Clinton'] ==>
|
|
789
|
+
['The Secretary of State', 'Hillary', 'Clinton']
|
|
790
|
+
|
|
791
|
+
When joining titles, saves newly formed piece to the instance's titles
|
|
792
|
+
constant so they will be parsed correctly later. E.g. after parsing the
|
|
793
|
+
example names above, 'The Secretary of State' and 'Mr. and Mrs.' would
|
|
794
|
+
be present in the titles constant set.
|
|
795
|
+
|
|
796
|
+
:param list pieces: name pieces strings after split on spaces
|
|
797
|
+
:param int additional_parts_count:
|
|
798
|
+
:return: new list with piece next to conjunctions merged into one piece
|
|
799
|
+
with spaces in it.
|
|
800
|
+
:rtype: list
|
|
801
|
+
|
|
802
|
+
"""
|
|
803
|
+
length = len(pieces) + additional_parts_count
|
|
804
|
+
# don't join on conjunctions if there's only 2 parts
|
|
805
|
+
if length < 3:
|
|
806
|
+
return pieces
|
|
807
|
+
|
|
808
|
+
rootname_pieces = [p for p in pieces if self.is_rootname(p)]
|
|
809
|
+
total_length = len(rootname_pieces) + additional_parts_count
|
|
810
|
+
|
|
811
|
+
# find all the conjunctions, join any conjunctions that are next to each
|
|
812
|
+
# other, then join those newly joined conjunctions and any single
|
|
813
|
+
# conjunctions to the piece before and after it
|
|
814
|
+
conj_index = [i for i, piece in enumerate(pieces)
|
|
815
|
+
if self.is_conjunction(piece)]
|
|
816
|
+
|
|
817
|
+
contiguous_conj_i = group_contiguous_integers(conj_index)
|
|
818
|
+
|
|
819
|
+
delete_i: list[int] = []
|
|
820
|
+
for cont_i in contiguous_conj_i:
|
|
821
|
+
new_piece = " ".join(pieces[cont_i[0]: cont_i[1]+1])
|
|
822
|
+
delete_i += list(range(cont_i[0]+1, cont_i[1]+1))
|
|
823
|
+
pieces[cont_i[0]] = new_piece
|
|
824
|
+
# add newly joined conjunctions to constants to be found later
|
|
825
|
+
self.C.conjunctions.add(new_piece)
|
|
826
|
+
|
|
827
|
+
for i in reversed(delete_i):
|
|
828
|
+
# delete pieces in reverse order or the index changes on each delete
|
|
829
|
+
del pieces[i]
|
|
830
|
+
|
|
831
|
+
if len(pieces) == 1:
|
|
832
|
+
# if there's only one piece left, nothing left to do
|
|
833
|
+
return pieces
|
|
834
|
+
|
|
835
|
+
# refresh conjunction index locations
|
|
836
|
+
conj_index = [i for i, piece in enumerate(pieces) if self.is_conjunction(piece)]
|
|
837
|
+
|
|
838
|
+
for i in conj_index:
|
|
839
|
+
if len(pieces[i]) == 1 and total_length < 4:
|
|
840
|
+
# if there are only 3 total parts (minus known titles, suffixes
|
|
841
|
+
# and prefixes) and this conjunction is a single letter, prefer
|
|
842
|
+
# treating it as an initial rather than a conjunction.
|
|
843
|
+
# http://code.google.com/p/python-nameparser/issues/detail?id=11
|
|
844
|
+
continue
|
|
845
|
+
|
|
846
|
+
if i == 0:
|
|
847
|
+
new_piece = " ".join(pieces[i:i+2])
|
|
848
|
+
if self.is_title(pieces[i+1]):
|
|
849
|
+
# when joining to a title, make new_piece a title too
|
|
850
|
+
self.C.titles.add(new_piece)
|
|
851
|
+
pieces[i] = new_piece
|
|
852
|
+
pieces.pop(i+1)
|
|
853
|
+
# subtract 1 from the index of all the remaining conjunctions
|
|
854
|
+
for j, val in enumerate(conj_index):
|
|
855
|
+
if val > i:
|
|
856
|
+
conj_index[j] = val-1
|
|
857
|
+
|
|
858
|
+
else:
|
|
859
|
+
new_piece = " ".join(pieces[i-1:i+2])
|
|
860
|
+
if self.is_title(pieces[i-1]):
|
|
861
|
+
# when joining to a title, make new_piece a title too
|
|
862
|
+
self.C.titles.add(new_piece)
|
|
863
|
+
pieces[i-1] = new_piece
|
|
864
|
+
pieces.pop(i)
|
|
865
|
+
rm_count = 2
|
|
866
|
+
try:
|
|
867
|
+
pieces.pop(i)
|
|
868
|
+
except IndexError:
|
|
869
|
+
rm_count = 1
|
|
870
|
+
|
|
871
|
+
# subtract the number of removed pieces from the index
|
|
872
|
+
# of all the remaining conjunctions
|
|
873
|
+
for j, val in enumerate(conj_index):
|
|
874
|
+
if val > i:
|
|
875
|
+
conj_index[j] = val - rm_count
|
|
876
|
+
|
|
877
|
+
# join prefixes to following lastnames: ['de la Vega'], ['van Buren']
|
|
878
|
+
prefixes = list(filter(self.is_prefix, pieces))
|
|
879
|
+
if prefixes:
|
|
880
|
+
for prefix in prefixes:
|
|
881
|
+
try:
|
|
882
|
+
i = pieces.index(prefix)
|
|
883
|
+
except ValueError:
|
|
884
|
+
# If the prefix is no longer in pieces, it's because it has been
|
|
885
|
+
# combined with the prefix that appears right before (or before that when
|
|
886
|
+
# chained together) in the last loop, so the index of that newly created
|
|
887
|
+
# piece is the same as in the last loop, i==i still, and we want to join
|
|
888
|
+
# it to the next piece.
|
|
889
|
+
pass
|
|
890
|
+
|
|
891
|
+
new_piece = ''
|
|
892
|
+
|
|
893
|
+
# join everything after the prefix until the next prefix or suffix
|
|
894
|
+
|
|
895
|
+
try:
|
|
896
|
+
if i == 0 and total_length >= 1:
|
|
897
|
+
# If it's the first piece and there are more than 1 rootnames, assume it's a first name
|
|
898
|
+
continue
|
|
899
|
+
next_prefix = next(iter(filter(self.is_prefix, pieces[i + 1:])))
|
|
900
|
+
j = pieces.index(next_prefix, i + 1)
|
|
901
|
+
if j == i + 1:
|
|
902
|
+
# if there are two prefixes in sequence, join to the following piece
|
|
903
|
+
j += 1
|
|
904
|
+
new_piece = ' '.join(pieces[i:j])
|
|
905
|
+
pieces = pieces[:i] + [new_piece] + pieces[j:]
|
|
906
|
+
except StopIteration:
|
|
907
|
+
try:
|
|
908
|
+
# if there are no more prefixes, look for a suffix to stop at
|
|
909
|
+
stop_at = next(iter(filter(self.is_suffix, pieces[i + 1:])))
|
|
910
|
+
j = pieces.index(stop_at)
|
|
911
|
+
new_piece = ' '.join(pieces[i:j])
|
|
912
|
+
pieces = pieces[:i] + [new_piece] + pieces[j:]
|
|
913
|
+
except StopIteration:
|
|
914
|
+
# if there were no suffixes, nothing to stop at so join all
|
|
915
|
+
# remaining pieces
|
|
916
|
+
new_piece = ' '.join(pieces[i:])
|
|
917
|
+
pieces = pieces[:i] + [new_piece]
|
|
918
|
+
|
|
919
|
+
log.debug("pieces: %s", pieces)
|
|
920
|
+
return pieces
|
|
921
|
+
|
|
922
|
+
# Capitalization Support
|
|
923
|
+
|
|
924
|
+
def cap_word(self, word: str, attribute: HumanNameAttributeT) -> str:
|
|
925
|
+
if (self.is_prefix(word) and attribute in ('last', 'middle')) \
|
|
926
|
+
or self.is_conjunction(word):
|
|
927
|
+
return word.lower()
|
|
928
|
+
exceptions = self.C.capitalization_exceptions
|
|
929
|
+
if lc(word) in exceptions:
|
|
930
|
+
return exceptions[lc(word)]
|
|
931
|
+
mac_match = self.C.regexes.mac.match(word)
|
|
932
|
+
if mac_match:
|
|
933
|
+
def cap_after_mac(m: re.Match) -> str:
|
|
934
|
+
return m.group(1).capitalize() + m.group(2).capitalize()
|
|
935
|
+
return self.C.regexes.mac.sub(cap_after_mac, word)
|
|
936
|
+
else:
|
|
937
|
+
return word.capitalize()
|
|
938
|
+
|
|
939
|
+
def cap_piece(self, piece: str, attribute: HumanNameAttributeT) -> str:
|
|
940
|
+
if not piece:
|
|
941
|
+
return ""
|
|
942
|
+
|
|
943
|
+
def replacement(m: re.Match) -> str:
|
|
944
|
+
return self.cap_word(m.group(0), attribute)
|
|
945
|
+
|
|
946
|
+
return self.C.regexes.word.sub(replacement, piece)
|
|
947
|
+
|
|
948
|
+
def capitalize(self, force: bool | None = None) -> None:
|
|
949
|
+
"""
|
|
950
|
+
The HumanName class can try to guess the correct capitalization of name
|
|
951
|
+
entered in all upper or lower case. By default, it will not adjust the
|
|
952
|
+
case of names entered in mixed case. To run capitalization on all names
|
|
953
|
+
pass the parameter `force=True`.
|
|
954
|
+
|
|
955
|
+
:param bool force: Forces capitalization of mixed case strings. This
|
|
956
|
+
parameter overrides rules set within
|
|
957
|
+
:py:class:`~nameparser.config.CONSTANTS`.
|
|
958
|
+
|
|
959
|
+
**Usage**
|
|
960
|
+
|
|
961
|
+
.. doctest:: capitalize
|
|
962
|
+
|
|
963
|
+
>>> name = HumanName('bob v. de la macdole-eisenhower phd')
|
|
964
|
+
>>> name.capitalize()
|
|
965
|
+
>>> str(name)
|
|
966
|
+
'Bob V. de la MacDole-Eisenhower Ph.D.'
|
|
967
|
+
>>> # Don't touch good names
|
|
968
|
+
>>> name = HumanName('Shirley Maclaine')
|
|
969
|
+
>>> name.capitalize()
|
|
970
|
+
>>> str(name)
|
|
971
|
+
'Shirley Maclaine'
|
|
972
|
+
>>> name.capitalize(force=True)
|
|
973
|
+
>>> str(name)
|
|
974
|
+
'Shirley MacLaine'
|
|
975
|
+
|
|
976
|
+
"""
|
|
977
|
+
name = str(self)
|
|
978
|
+
force = self.C.force_mixed_case_capitalization \
|
|
979
|
+
if force is None else force
|
|
980
|
+
|
|
981
|
+
if not force and not (name == name.upper() or name == name.lower()):
|
|
982
|
+
return
|
|
983
|
+
self.title_list = self.cap_piece(self.title, 'title').split(' ')
|
|
984
|
+
self.first_list = self.cap_piece(self.first, 'first').split(' ')
|
|
985
|
+
self.middle_list = self.cap_piece(self.middle, 'middle').split(' ')
|
|
986
|
+
self.last_list = self.cap_piece(self.last, 'last').split(' ')
|
|
987
|
+
self.suffix_list = self.cap_piece(self.suffix, 'suffix').split(', ')
|
|
988
|
+
|
|
989
|
+
def handle_capitalization(self) -> None:
|
|
990
|
+
"""
|
|
991
|
+
Handles capitalization configurations set within
|
|
992
|
+
:py:class:`~nameparser.config.CONSTANTS`.
|
|
993
|
+
"""
|
|
994
|
+
if self.C.capitalize_name:
|
|
995
|
+
self.capitalize()
|