在Python中提取名字和姓氏
我试图在一篇大文章(大约20页)中提取所有的名字和姓氏(例如:约翰·约翰逊) 我使用带在Python中提取名字和姓氏,python,regex,extract,Python,Regex,Extract,我试图在一篇大文章(大约20页)中提取所有的名字和姓氏(例如:约翰·约翰逊) 我使用带\.的拆分作为分隔符,下面是我的正则表达式: \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 有人能帮我吗?试试看 regex = re.c
\.
的拆分作为分隔符,下面是我的正则表达式:
\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
有人能帮我吗?试试看
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')]
我采用了一个正则表达式,它可以处理重音和组合名称的破折号:
#!/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))
[nsregularexpression]
与Python有什么关系?使用
作为分隔符进行拆分是什么意思
表示任何字符,您的任务似乎是搜索,而不是拆分。你向你提到的正则表达式提供了什么输入?在你提到的模式和句子上直接使用re.search
,会将名称识别为(“玛丽”、“波宾斯”)
。注意{1}
是隐式的\s
和\s{1}
都只匹配一个字符。您定义姓名和姓氏的规则是什么?我们必须期望他们是什么样子?所有的名字和姓氏都以大写字母开头,或者姓氏都是大写字母?你打算如何将名字或姓氏与逗号后的第一个单词或句子开头的第一个单词(因此以大写字母开头)区分开来?我建议先阅读,然后放弃。