【问题标题】:Extracting first name and last name in Python在Python中提取名字和姓氏
【发布时间】:2013-12-03 14:35:34
【问题描述】:

我正在尝试提取一个大文本(大约 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

有人可以帮我吗?

【问题讨论】:

  • [nsregularexpression] 和 Python 有什么关系?
  • .作为分隔符是什么意思? . 表示任何字符,您的任务似乎是搜索,而不是拆分。您提供给您提到的正则表达式的输入是什么?在您提到的模式和句子上直接使用re.search 确实将名称标识为("Mary ", "Poppins")
  • 注意{1}是隐含的; \s\s{1} 都只匹配一个字符。
  • 您定义姓名和姓氏的规则是什么?我们必须期待他们是什么样的?所有的名字和姓氏都以大写开头还是姓氏都是大写?您打算如何将姓名或姓氏与逗号后或句子开头的第一个单词(因此以大写开头)分开?
  • 我建议阅读kalzumeus.com/2010/06/17/…然后放弃。

标签: python regex extract


【解决方案1】:

我已经调整了一个正则表达式,它可以处理组合名称的重音和破折号:

#!/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))

【讨论】:

    【解决方案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')]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多