2012-03-24 116 views
0

我正在尝试使用Python 2.7正则表达式来从我正在使用的课程中提供的示例网页中检索数据。我试图去工作的代码是:Python RE,AttributeError:'元组'对象没有属性'组'

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对象。

这里发生了什么,以及如何通过使用命名组来正确工作?

+2

[ “正则表达式的检索来自样品网页上的数据”(http://stackoverflow.com/questions/1732348/regex-match-open-tags- except-xhtml-self-contained-tags/1732454#1732454) – 2012-03-24 05:06:38

回答

2

你有两个问题。像Ignacio暗示的那样,你不应该用正则表达式来解析(X)HTML ......正则表达式不能处理复杂性。另一个问题是您正在使用findall()而不是finditer()findall()将匹配作为列表返回......在组发生事件时,它将其作为元组列表返回。

finditer()另一方面返回具有group()方法的MatchGroup对象的迭代器。

re Python文档:

re.findall(pattern, string, flags=0) Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

re.finditer(pattern, string, flags=0) Return an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in string. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result unless they touch the beginning of another match.

+0

这就是其他两个问题中的*。 – 2012-03-24 05:19:45

+0

可能值得一提的是BeautifulSoup或类似的库作为正则表达式的可能解决方案。 – 2012-03-24 05:22:41

+0

谢谢,迈克尔。这非常有帮助。我会尝试re.finditer。关于正则表达式在我的场景中是否合适:事实上,它们是。原因如下:这是专注于使用Python和正则表达式的课程任务的一部分。需要使用Python和正则表达式。如果我不使用它们,我不会获得功劳。 :-) – Ussabin 2012-03-24 20:19:44

相关问题