2014-04-28 40 views
0

我有一个名为“FILENAME.TXT”文件Python的正则表达式NoneType错误

内容的文本文件:

This is just a text 
    content to store 
    in a file. 

我已经做了两个Python脚本来提取“到”从文本文件

我的第一脚本:

 #!/usr/bin/python 
    import re 
    f = open("filename.txt","r") 
    for line in f: 
       text = re.match(r"content (\S+) store",line) 
       x = text.group(1) 
       print x 

我的第二个脚本:

#!/usr/bin/python 
    import re 
    f = open("filename.txt","r") 
    for line in f: 
      text = re.match(r"content (\S+) store",line) 
      if text: 
        x = text.group(1) 
        print x 

第二脚本提供了正确的输出

bash-3.2$ ./script2.py 
to 

但第一次剧本给我一个错误

bash-3.2$ ./script1.py 
Traceback (most recent call last): 
File "./script1.py", line 6, in ? 
x = text.group(1) 
AttributeError: 'NoneType' object has no attribute 'group' 

怎么就是添加一个“如果”条件给我正确的输出,当我删除它我得到一个错误?

回答

1

这个错误对我来说是不言而喻的:re.match如果找不到匹配项返回None(请参阅doc)。

所以,当你的正则表达式不匹配(例如第一行)时,你试图访问NoneType对象的group属性,它会抛出一个错误。

在另一种情况下,如果text不是None(因为这是if text:检查等等),您只能访问该属性。

1

这是因为在您的第一个代码中,您的正则表达式无法匹配任何内容,因此textNoneType。当你尝试做group它抛出AttributeError: 'NoneType' object has no attribute 'group'错误

然而,对于您正则表达式,您的代码不会失败,因为你小心调用group只好像有些实际上匹配

你的第二个方法是更好,因为它不像第一个那样可靠。