3

我有一组名字,其中姓氏大写,名字和中间名是正常的,例如

OBAMA Barack
DEL MONTE Alfredo

我想把这些分成

"OBAMA", "Barack"
"DEL MONTE", "Alfredo"

实现这一目标的pythonic方法是什么?

4

4 回答 4

8
>>> import itertools
>>> [
...    ' '.join(items)
...    for _, items in itertools.groupby('DEL MONTE Alfredo'.split(), str.isupper)
... ]
['DEL MONTE', 'Alfredo']
于 2012-04-30T07:44:00.330 回答
2
def split_names(names):
    for s in names:
        last_names = []
        name_parts = s.split()
        while name_parts and name_parts[0].isupper():
            last_names.append(name_parts.pop(0))
        yield ' '.join(last_names), ' '.join(name_parts)


names = ["OBAMA Barack", "DEL MONTE Alfredo"]
for last_name, first_name in split_names(names):
    print last_name
    print first_name
    print

印刷:

OBAMA
Barack

DEL MONTE
Alfredo
于 2012-04-30T07:43:17.737 回答
2

您可以使用一个简单的正则表达式:

import re

a = "DEL MONTE Alfredo"
first, last = re.match(r'([A-Z ]+)\s+(.+)', a).groups()

或遍历单词列表并过滤掉全部大写的单词:

first = ' '.join(w for w in a.split() if w.isupper())
last =  ' '.join(w for w in a.split() if not w.isupper())

在我个人看来,“最pythonic”===“最简单”。

于 2012-04-30T09:04:52.570 回答
0

试试这个:

(?![A-Z][a-z])([A-Z ]+) ([A-Z][a-z]+)
于 2012-04-30T07:44:29.740 回答