用“,”或“和”分隔的列表的正则表达式

2024-03-28 20:27:14 发布

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

我有一个很长的引文列表,我需要提取每个作者的全名、发表年份、标题等。其中一个引文如下所示:

Joe Bob, Jane Doe and George H. Smith (2017). A title of an interesting report: Part 2. Report Series no. 101, Place for Generating Reports, Department of Report Makers, City, Province, Country, 44 pages. ISBN: (print) 123-0-1234-1234-5; (online) 123-0-1234-1234-5.

所有引文的格式都是一样的。我现在坚持的部分是提取作者的全名。我在这里读到了如何从逗号、空格或分号分隔的列表here中提取值,方法类似于[\\s,;]+。我该如何对逗号或“and”这个词做类似的处理?你知道吗

我假设‘and’需要像一组字符一样对待,所以我尝试[^,|[and])]+匹配,或字符集[and]之间的空格,但这似乎不起作用。这个question类似于处理逗号或空格,但解决方案涉及隐式剥离空格。你知道吗

在完成这一部分之后,我计划构建表达式的其余部分,以捕获其他引用细节。假设我们要处理的字符串是:

Joe Bob, Jane Doe and George H. Smith

每个全名都应该被捕获。你知道吗


Tags: andofreport标题列表作者bobsmith
1条回答
网友
1楼 · 发布于 2024-03-28 20:27:14

以下是一种可能的方法:

citation = """Joe Bob, Jane Doe and George H. Smith (2017). A title of an interesting report: Part 2. Report Series no. 101, Place for Generating Reports, Department of Report Makers, City, Province, Country, 44 pages. ISBN: (print) 123-0-1234-1234-5; (online) 123-0-1234-1234-5."""

citation = citation.replace(' and ', ',')
citation = citation[:citation.find('(')]

names = [name.strip() for name in citation.split(',')]

print names

给你:

['Joe Bob', 'Jane Doe', 'George H. Smith']

and转换成逗号,切分到年份开始的地方,用逗号分开。你知道吗

或者以更紧凑的形式:

names = [name.strip() for name in citation[:citation.find('(')].replace(' and ', ',').split(',')]

相关问题 更多 >