2013-03-05 36 views
15

我有一個字符串,我想提取的一個子集。這是一個更大的Python腳本的一部分。Python +正則表達式:AttributeError:'NoneType'對象沒有屬性'組'

這是字符串:

import re 

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)' 

,我要拔出 「蛻皮是gràcies莫爾behh,GRAH-syuhs」。爲此,我用使用re.search正則表達式:

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))' 

Result = re.search(SearchStr, htmlString) 

print Result.groups() 
AttributeError: 'NoneType' object has no attribute 'groups' 

由於Result.groups()不工作,我也不想讓提取(即Result.group(5)Result.group(7))。 但我不明白爲什麼我會得到這個錯誤?正則表達式在TextWrangler中工作,爲什麼不在Python中?我是一個Python初學者。

+0

嘗試將您的'htmlString'解碼爲Unicode – thkang 2013-03-05 20:18:32

回答

7
import re 

htmlString = '</dd><dt> Fine, thank you.&#160;</dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)' 

SearchStr = '(\<\/dd\>\<dt\>)+ ([\w+\,\.\s]+)([\&\#\d\;]+)(\<\/dt\>\<dd\>)+ ([\w\,\s\w\s\w\?\!\.]+) (\(\<i\>)([\w\s\,\-]+)(\<\/i\>\))' 

Result = re.search(SearchStr.decode('utf-8'), htmlString.decode('utf-8'), re.I | re.U) 

print Result.groups() 

作品的方式。該表達式包含非拉丁字符,因此通常會失敗。你必須解碼爲Unicode並使用re.U(Unicode)標誌。

我也是初學者,我自己也遇到過這個問題。

31

您正在獲取AttributeError,因爲您在None上調用groups,它沒有任何方法。

regex.search返回None表示正則表達式無法找到與提供的字符串中的模式相匹配的任何內容。

使用正則表達式時

,它是好的,檢查是否匹配已經做出:

Result = re.search(SearchStr, htmlString) 

if Result: 
    print Result.groups() 
+0

似乎是轉義(()中的()的問題(GRAH-syuhs)。我已經嘗試了'\''和'\\('但都沒有工作。 – 2013-03-06 08:52:35