如何在单词后和字符前获取列表

2024-09-30 14:28:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我现在有这个字符串,我想把名字提取出来,例如,Garet Hayes,Ronald Allen,等等

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

我可以通过以下代码提取名字Garet Hayes:

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

但我觉得应该有一种更有效的方法,即使只取第一个名字,更不用说第二个或其他名字了。我该怎么办


Tags: and字符串indexdocvice名字chiefallen
3条回答

类似于@azro使用列表理解的解决方案:

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

你们需要把你们的内容分成几行,然后每一行在短划线上分开,并保留第一部分

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']

您也可以使用regex

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

使用正则表达式:


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']

相关问题 更多 >