在Python中提取名字和姓氏

时间:2013-12-03 14:35:34

标签: python regex extract

我正在尝试以大文本(约20页)提取所有名字和姓氏(例如:John Johnson)。

我使用split \.作为分隔符,并且有正则表达式:

\b([A-Z]{1}[a-z]+\s{1})([A-Z]{1}[a-z]+)\b

不幸的是,我只获得了我的文本的所有行,而不是只有名字和姓氏:

Suddenly, Mary Poppins flew away with her umbrella
Later in the day, John.... bla bla bla

有人可以帮助我吗?

2 个答案:

答案 0 :(得分:2)

尝试

regex = re.compile("\b([A-Z]{1}[a-z]+) ([A-Z]{1}[a-z]+)\b")
string = """Suddenly, Mary Poppins flew away with her umbrella
Later in the day, John Johnson did something."""
regex.findall(string)

我得到的输出是:

[(u'Mary', u'Poppins'), (u'John', u'Johnson')]

答案 1 :(得分:0)

我已经改编了一个可以处理重音和破折号的正则表达式:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
r = re.compile('([A-Z]\w+(?=[\s\-][A-Z])(?:[\s\-][A-Z]\w+)+)',
           re.UNICODE)
tests = {
    u'Jean Vincent Placé': u'Jean Vincent Placé est un excellent donneur de leçons',
    u'Giovanni Delle Bande Nere': u'In quest\'anno Giovanni Delle Bande Nere ha avuto tre momenti di gloria',
    # Here 'BDFL' may not be whished
    u'BDFL Guido Van Rossum': u'Nobody hacks Python like BDFL Guido Van Rossum because he created it'
}
for expected, s in tests.iteritems():
    match = r.search(s)
    assert(match is not None)
    extracted = match.group(0)
    print expected
    print extracted
    assert(expected == match.group(0))