我是Python的新手,并且有一个由名字分隔的名单\and,我需要加入,用逗号分隔第一个,用'和'分隔最后一个.但是,如果有超过4个名称,则返回值应该是第一个名称以及短语"et al.".所以,如果我有
authors = 'John Bar \and Tom Foo \and Sam Foobar \and Ron Barfoo'
Run Code Online (Sandbox Code Playgroud)
我应该得到'约翰巴尔等人'.而与
authors = 'John Bar \and Tom Foo \and Sam Foobar'
Run Code Online (Sandbox Code Playgroud)
我应该得到'John Bar,Tom Foo和Sam Foobar'.
它也应该只使用一个作者名称,单独返回该单个名称(和姓氏).
我试过做类似的事情
names = authors.split('\and')
result = ', '.join(names[:-1]) + ' and '.join(names[-1])
Run Code Online (Sandbox Code Playgroud)
但这显然不起作用.所以我的问题是我如何使用join和split得到第一个作者用逗号分隔,最后用'和'考虑如果有超过四个作者,只有第一个作者名称应该与'等人'一起返回. .
首先拆分名称:
names = [name.strip() for name in authors.split(r'\and')] # assuming a raw \ here, not the escape code \a.
Run Code Online (Sandbox Code Playgroud)
然后根据长度重新加入:
if len(names) >= 4:
authors = '{} et al.'.format(names[0])
elif len(names) > 1:
authors = '{} and {}'.format(', '.join(names[:-1]), names[-1])
else:
authors = names[0]
Run Code Online (Sandbox Code Playgroud)
这适用于只有一位作者的作品; 我们只是将名称重新分配给authors.
组合成一个功能:
def reformat_authors(authors):
names = [name.strip() for name in authors.split(r'\and')]
if len(names) >= 4:
return '{} et al.'.format(names[0])
if len(names) > 1:
return '{} and {}'.format(', '.join(names[:-1]), names[-1])
return names[0]
Run Code Online (Sandbox Code Playgroud)
用演示:
>>> reformat_authors(r'John Bar \and Tom Foo \and Sam Foobar \and Ron Barfoo')
'John Bar et al.'
>>> reformat_authors(r'John Bar \and Tom Foo \and Sam Foobar')
'John Bar, Tom Foo and Sam Foobar'
>>> reformat_authors(r'John Bar \and Tom Foo')
'John Bar and Tom Foo'
>>> reformat_authors(r'John Bar')
'John Bar'
Run Code Online (Sandbox Code Playgroud)