2012-03-24 117 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

相關問題