我有一个名为“的文本文件”文件名.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”条件来获得正确的输出,当我删除它时,我会得到一个错误?
这个错误对我来说是不言而喻的:
re.match
如果没有找到匹配项,则返回None
(请参见doc)。在因此,当您的regex不匹配时(例如第一行),您试图访问
NoneType
对象的group
属性,它会抛出一个错误。在在另一种情况下,仅当}时才访问该属性(因为这是
text
不是{if text:
检查的内容之一)。在这是因为在第一段代码中,正则表达式无法匹配任何内容,因此
text
是NoneType
。当您尝试执行group
时,它抛出AttributeError: 'NoneType' object has no attribute 'group'
错误但是,对于regex,代码不会失败,因为只有在某个实际上匹配的情况下才小心地调用
group
你的第二种方法更好,因为它不像第一种方法那样是防失败的。在
相关问题 更多 >
编程相关推荐