Skip to content

Instantly share code, notes, and snippets.

@gfrlv
Last active September 4, 2023 11:22
Show Gist options
  • Save gfrlv/726e93da91211182f1d01e7d28211aeb to your computer and use it in GitHub Desktop.
Save gfrlv/726e93da91211182f1d01e7d28211aeb to your computer and use it in GitHub Desktop.
Разбор ФИО в именительном падеже
from collections import namedtuple
from yargy import (
rule,
and_, or_, not_,
Parser
)
from yargy.interpretation import fact
from yargy.predicates import (
eq, gram
)
from yargy.predicates.bank import DictionaryPredicate as dictionary
Name = fact(
'Name',
['first', 'middle', 'last']
)
WORD = not_(or_(gram('Patr'), gram('Abbr'), gram('Name'), gram('Surn')))
PATRONYMIC = gram('Patr')
SYNTACTIC_NAME = and_(gram('Name'), gram('nomn'), not_(gram('Abbr')))
LAST_NAME_PART = and_(
not_(gram('Abbr')),
or_(
gram('Surn'),
PATRONYMIC,
SYNTACTIC_NAME,
gram('ADJF'),
WORD
)
)
FIRST_NAME = and_(
not_(gram('Abbr')),
or_(
and_(gram('Name'), not_(gram('Surn'))),
gram('NOUN')
)
).interpretation(Name.first)
LAST_NAME = rule(
LAST_NAME_PART,
rule(
eq('-'),
LAST_NAME_PART
).optional()
).interpretation(Name.last)
MIDDLE_NAME = PATRONYMIC.interpretation(Name.middle)
FIRST_ABBR = rule(gram('Abbr')).interpretation(Name.first)
MIDDLE_ABBR = rule(gram('Abbr')).interpretation(Name.middle)
DOT = or_(eq('.'), eq(','))
NAME = or_(
rule(LAST_NAME, FIRST_NAME, MIDDLE_NAME),
rule(LAST_NAME, FIRST_NAME),
rule(LAST_NAME, FIRST_ABBR, DOT.optional()),
rule(LAST_NAME, FIRST_ABBR, DOT.optional(), MIDDLE_ABBR, DOT.optional()),
rule(LAST_NAME),
rule(FIRST_NAME, LAST_NAME),
rule(FIRST_NAME, MIDDLE_NAME, LAST_NAME),
rule(FIRST_ABBR, DOT.optional(), MIDDLE_ABBR, DOT.optional(), LAST_NAME),
rule(FIRST_ABBR, DOT.optional(), LAST_NAME),
).interpretation(Name)
PersonName = namedtuple('PersonName', ['first', 'middle', 'last'])
NAME_PARSER = Parser(NAME)
def parse_person_name(name_str):
matches = NAME_PARSER.findall(name_str)
try:
match = next(matches)
except StopIteration:
return PersonName(None, None, None)
fact = match.fact
return PersonName(fact.first, fact.middle, fact.last)
examples = [
'Богданович Анжелика Георгиевна',
'Азина Виктория Владимировна',
'Виктория Владимировна Азина',
'Анжелика Георгиевна Богданович',
'Панцирев Ю.И.',
'Шагеев Г.Х',
'Булгакова Раушана Юнусовна',
'ГОРШИЛИНА НАТАЛЬЯ АЛЕКСАНДРО',
'Хирургическое отделение',
'ЕРМАКОВА СКОРАЯ НАТАЛЬЯ ВАСИЛЬЕВНА',
'Ольга Николаевна Некрасова-Коротеева',
'КОЧЕВА МОДЕРНИЗАЦИЯ',
'МОИСЕЕНКО АНТОНИДА КУЗМИНИЧНА',
'РУДНЕВА ВАЛЕНТИНА МИХАЙЛОВН',
'КОЧЕТКОВА ВАЛЕНТИНА АНИСИМОВН',
'Кочеткова Валентина Анисимов',
'Кочеткова Валентина Анисимовн',
'КОЧЕТКОВА ВАЛЕНТИНА АНИСИМОВНА',
'Кочеткова Валентина А',
'Кочеткова Валентина Абракадабра',
'Михаил Сергеевич Кузмич',
'КОЧЕВА МОДЕРНИЗАЦИЯ',
'КРАВЧУК ГАЛИНА НИКИТИЧНА'
]
for ex in examples:
print(ex, parse_person_name(ex))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment