简体   繁体   中英

How to get a list after a word and before a character

I currently have this string and I would like to extract the names out, for example, Garet Hayes, Ronald Allen, etc.

Executives
Garet Hayes - Director, Public Relations
Ronald Allen - Chief Executive Officer
Gilbert Danielson - Executive Vice President and Chief Financial Officer
Steven Michaels - President
John Robinson - Executive Vice President and President and Chief Executive Officer, Progressive Finance Holdings LLC

I am able to extract the first name, Garet Hayes, by this code:

def partiesExtractor(doc):
    executives = []
    executives.append(doc[doc.lower().index('executives') + len('executives') + 1 : doc.index(' -')])
    return executives

But I feel like there should be a more efficient way even just to get the first name, let alone the second or the rest of the list. How do I go about this?

You need to split your content in lines, then for each one split on dash, and keep first part

def partiesExtractor(doc):
    executives = []
    for line in doc.splitlines()[1:]:
        executives.append(line.split("-")[0].strip())
    return executives
    # return [line.split("-")[0].strip() for line in doc.splitlines()[1:]] # list-comprenhension


text = """Executives
Garet Hayes - Director, Public Relations
Ronald Allen - Chief Executive Officer
Gilbert Danielson - Executive Vice President and Chief Financial Officer
Steven Michaels - President
John Robinson - Executive Vice President and President and Chief Executive 
Officer, Progressive Finance Holdings LLC"""

print(partiesExtractor(text))  # ['Garet Hayes', 'Ronald Allen', 'Gilbert Danielson', 'Steven Michaels', 'John Robinson']

You can use a regex too

def partiesExtractor(doc):
    return re.findall("^[A-Z][a-z]+ [A-Z][a-z]+", doc, flags=re.MULTILINE)

Similar solution as @azro using a list comprehension:

def partiesExtractor(doc):
  return [line.split(" - ")[0] for line in doc.split("\n")[1:]]

using regex:


import re

s = '''Executives
Garet Hayes - Director, Public Relations
Ronald Allen - Chief Executive Officer
Gilbert Danielson - Executive Vice President and Chief Financial Officer
Steven Michaels - President
John Robinson - Executive Vice President and President and Chief Executive Officer, Progressive Finance Holdings LLC'''

reg = '(\w+\s\w+)\s-\s'

names = re.findall(reg,s)
print(names)

['Garet Hayes', 'Ronald Allen', 'Gilbert Danielson', 'Steven Michaels', 'John Robinson']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM