【发布时间】:2012-03-24 05:04:28
【问题描述】:
我正在尝试使用 Python 2.7 正则表达式从我正在学习的课程中提供的示例网页中检索数据。我要开始工作的代码是:
email_patterns = ['(?P<lname>[\w+\.]*\w+ *)@(?P<domain> *\w+[\.\w+]*).(?P<tld>com)
for pattern in email_patterns:
# 'line' is a line of text in a sample web page
matches = re.findall(pattern,line)
for m in matches:
print 'matches=', m
email = '{}@{}.{}'.format(m.group('lname'), m.group('domain'),m.group('tld'))
运行它会返回以下错误:
email = '{}@{}.{}'.format(m.group('lname'), m.group('domain'), m.group('tld'))
AttributeError: 'tuple' object has no attribute 'group'.
我想使用命名组,因为组的顺序可以根据我匹配的文本而改变。但是,它似乎不起作用,因为编译器认为 'm' 不是 Group 对象。
这里发生了什么,我怎样才能通过使用命名组使其正常工作?
【问题讨论】:
标签: python regex python-2.7