How do I parse the people's first and last name in Python?

I found this library quite useful for parsing names. https://code.google.com/p/python-nameparser/

It can also deal with names that are formatted Lastname, Firstname.


Well, for your simple example names, you can do something like this.

# This separates the first and last names
name = name.partition(" ")
firstName = name[0]
# now figure out the first initial
# we're assuming that if it has a dot it's an initialized name,
# but this may not hold in general
if "." in firstName:
    firstInitial = firstName
else:
    firstInitial = firstName[0] + "."
lastName = name[2]
return {"FirstName":firstName, "FirstInitial":firstInitial, "LastName": lastName}

I haven't tested it, but a function like that should do the job on the input example you provided.


There is no general solution and solution will depend on the constraints you put. For the specs you have given here is a simple solution which gives exactly what you want

def parse_name(name):
   fl = name.split()
   first_name = fl[0]
   last_name = ' '.join(fl[1:])
   if "." in first_name:
      first_initial = first_name
   else:
      first_initial = first_name[0]+"."

   return {'FirstName':first_name, 'FirstInitial':first_initial, 'LastName':last_name}

names = ["D.J. Richies III", "John Doe", "A.J. Hardie Jr."]
for name in names:
   print parse_name(name)

output:

{'LastName': 'Richies III', 'FirstInitial': 'D.J.', 'FirstName': 'D.J.'}
{'LastName': 'Doe', 'FirstInitial': 'J.', 'FirstName': 'John'}
{'LastName': 'Hardie Jr.', 'FirstInitial': 'A.J.', 'FirstName': 'A.J.'}

Tags:

Python

Parsing