Python正则表达式NoneTyp

2024-04-19 01:35:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为“的文本文件”文件名.txt““

文件内容:

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

我制作了两个python脚本从文本文件中提取“to”

我的第一个剧本:

^{pr2}$

我的第二个剧本:

    #!/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'

如何添加一个“if”条件来获得正确的输出,当我删除它时,我会得到一个错误?


Tags: tostoretextinpyretxt脚本
2条回答

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

因此,当您的regex不匹配时(例如第一行),您试图访问NoneType对象的group属性,它会抛出一个错误。在

在另一种情况下,仅当text不是{}时才访问该属性(因为这是if text:检查的内容之一)。在

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

但是,对于regex,代码不会失败,因为只有在某个实际上匹配的情况下才小心地调用group

你的第二种方法更好,因为它不像第一种方法那样是防失败的。在

相关问题 更多 >