Bryan Lee
Bryan Lee

Reputation: 25

Regex for name extraction on text file

I've got a plain text file containing a list of authors and abstracts and I'm trying to extract just the author names to use for network analysis. My text follows this pattern and contains 500+ abstracts:

2010 - NUCLEAR FORENSICS OF SPECIAL NUCLEAR MATERIAL AT LOS ALAMOS: THREE RECENT STUDIES 

Purchase this article

David L. Gallimore, Los Alamos National Laboratory

Katherine Garduno, Los Alamos National Laboratory

Russell C. Keller, Los Alamos National Laboratory

Nuclear forensics of special nuclear materials is a highly specialized field because there are few analytical laboratories in the world that can safely handle nuclear materials, perform high accuracy and precision analysis using validated analytical methods.

I'm using Python 2.7.6 with the re library.

I've tried

regex = re.compile(r'( [A-Z][a-z]*,+)')
print regex.findall(text)

Which pulls out the last names only, plus any capitalized words prior to commas in the abstracts.

Using (r'.*,') works perfectly to extract the full name, but also grabs the entire abstract which I don't need.

Maybe regex is the wrong approach? Any help or ideas are appreciated.

Upvotes: 1

Views: 2857

Answers (2)

hwnd
hwnd

Reputation: 70722

If you are trying to match the names, I would try to match the entire substring instead of part of it.

You could use the following regular expression and modify it if needed.

>>> regex = re.compile(r'\b([A-Z][a-z]+(?: [A-Z]\.)? [A-Z][a-z]+),')
>>> print regex.findall(text)
['David L. Gallimore', 'Katherine Garduno', 'Russell C. Keller']

Working Demo | Explanation

Upvotes: 2

DrinkBird
DrinkBird

Reputation: 834

try this one

[A-Za-z]* ?([A-Za-z]+.) [A-Za-z]*(?:,+)

It makes the middle name optional, plus it excludes the comma from the result by putting it in a non capturing group

Upvotes: 0

Related Questions