2

我想从字符串中匹配可能的名称。名称应为 2-4 个单词,每个单词包含 3 个或更多字母,所有单词大写。例如,给定以下字符串列表:

Her name is Emily.
I work for Surya Soft.
I sent an email for Ery Wulandari.
Welcome to the Link Building Partner program!

我想要一个返回的正则表达式:

None
Surya Soft
Ery Wulandari
Link Building Partner

目前这是我的代码:

data = [
   'Her name is Emily.', 
   'I work for Surya Soft.', 
   'I sent an email for Ery Wulandari.', 
   'Welcome to the Link Building Partner program!'
]

for line in data:
    print re.findall('(?:[A-Z][a-z0-9]{2,}\s+[A-Z][a-z0-9]{2,})', line)

它适用于前三行,但在最后一行失败。

4

4 回答 4

2

您可以使用:

re.findall(r'((?:[A-Z]\w{2,}\s*){2,4})', line)

它可能会添加一个可以修剪的尾随空格.strip()

于 2013-06-06T04:18:13.027 回答
2

您可以将分组用于重复结构,如下所示:

compiled = re.compile('(?:(([A-Z][a-z0-9]{2,})\s*){2,})')
for line in data:
    match = compiled.search(line)
    if match:
       print match.group()
    else:
       print None

输出:

None
Surya Soft
Ery Wulandari
Link Building Partner 
于 2013-06-06T04:30:46.747 回答
1

非正则表达式解决方案:

from string import punctuation as punc
def solve(strs):
   words = [[]]
   for i,x in enumerate(strs.split()):
      x = x.strip(punc)
      if x[0].isupper() and len(x)>2:
         if words[-1] and words[-1][-1][0] == i-1:
            words[-1].append((i,x))
         else:
            words.append([(i,x)])

   names = [" ".join(y[1] for y in x) for x in words if 2 <= len(x) <= 4]
   return ", ".join(names) if names else None


data = [
   'Her name is Emily.', 
   'I work for Surya Soft.', 
   'I sent an email for Ery Wulandari.', 
   'Welcome to the Link Building Partner abc Fooo Foo program!'
]
for x in data:
   print solve(x)

输出:

None
Surya Soft
Ery Wulandari
Link Building Partner, Fooo Foo
于 2013-06-06T04:21:24.583 回答
0
for line in data:
    print re.findall("[A-Z][\w]+", line)
于 2013-06-06T04:19:33.760 回答