正则表达式:AttributeError: 'NoneType'对象没有属性'groups
我有一个字符串,想从中提取一部分。这是一个更大Python脚本的一部分。
这个字符串是:
import re
htmlString = '</dd><dt> Fine, thank you. </dt><dd> Molt bé, gràcies. (<i>mohl behh, GRAH-syuhs</i>)'
我想提取出 "Molt bé, gràcies. mohl 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的初学者。
2 个回答
61
你遇到的 AttributeError
错误是因为你在对 None
调用 groups
,而 None
是没有任何方法的。
regex.search
返回 None
意味着正则表达式没有在提供的字符串中找到任何匹配的内容。
在使用正则表达式时,检查是否找到了匹配的内容是个好习惯:
Result = re.search(SearchStr, htmlString)
if Result:
print Result.groups()
14
import re
htmlString = '</dd><dt> Fine, thank you. </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)这个标志。
我也是个初学者,我自己也遇到过这个问题几次。