将作者姓名与第一个名字之间用逗号分隔,最后一个名字之间用“和"连接. [英] Join author names with first ones separated by comma and last one by "and"

查看:138
本文介绍了将作者姓名与第一个名字之间用逗号分隔,最后一个名字之间用“和"连接.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Python完全陌生,并且有一个用\and分隔的名称列表,我需要将它们的第一个以逗号分隔,最后一个以'and'分隔.但是,如果名称超过4个,则返回值应为名字以及短语"et al.".所以如果我有

I'm completely new to Python and have a list of names separated by \and, which I need to join separating the first ones with comma and the last one by 'and'. However if there are more than 4 names the return value should be the first name along with the phrase 'et al.'. So if I have

 authors = 'John Bar \and Tom Foo \and Sam Foobar \and Ron Barfoo'

我应该得到'John Bar et ..'.而

I should get 'John Bar et al.'. Whereas with

authors = 'John Bar \and Tom Foo \and Sam Foobar'

我应该得到约翰·巴,汤姆·富和山姆·富巴".

I should get 'John Bar, Tom Foo and Sam Foobar'.

它也应该仅使用一个作者姓名,并单独返回该单个姓名(和姓氏).

It should also work with just one author name, returning that single name (and surname) by itself.

我尝试做类似的事情

  names = authors.split('\and')
  result = ', '.join(names[:-1]) + ' and '.join(names[-1])

但这显然行不通.所以我的问题是我如何使用joinsplit来使第一个作者用逗号分隔,最后一个作者用'and'分隔,同时考虑到如果有四个以上的作者,则仅应返回第一个作者名称与等".

But that obviously doesn't work. So my question is how can I use join and split to get the first authors separated by comma and the last by 'and' taking into account that if there are more than four authors only the first author name should be returned along with 'et al.'.

推荐答案

首先拆分名称:

names = [name.strip() for name in authors.split(r'\and')]  # assuming a raw \ here, not the escape code \a.

然后根据长度重新加入:

Then rejoin based on the length:

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]

这也适用于只有一个作者的条目;我们只是将名称重新分配给authors.

This works for entries with just one author too; we just reassign the name to 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]

带有演示:

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

这篇关于将作者姓名与第一个名字之间用逗号分隔,最后一个名字之间用“和"连接.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆