2013-03-05 74 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

相关问题