提问人:JohnDoe 提问时间:11/17/2023 更新时间:11/17/2023 访问量:25
Python:.group “AttributeError:'NoneType'对象没有属性'group'”
Python: .group "AttributeError: 'NoneType' object has no attribute 'group'"
问:
当我将.group()放在“FOR”循环中时,出现错误。
import re
with open(r'C:\Users\testuser\OneDrive - personal\Network\network.log', 'r+') as LOG:
OUTPUT = LOG.readlines()
for LINE in OUTPUT:
x = re.search(r'\s+name ".*"', LINE).group()
print(x)
x = re.search(r'\s+name ".*"', LINE).group()
AttributeError: 'NoneType' object has no attribute 'group'
Process finished with exit code 1
但是,如果我简单地删除“.group()”,脚本将按预期执行。但是,我不希望值 None 或 **<re。匹配对象;span=(0, 30), match=' name “默认访问规则”'> ** 我只想返回与模式匹配的值。
答:
2赞
ssr765
11/17/2023
#1
您需要检查某些行中是否没有匹配项。
import re
with open(r'C:\Users\testuser\OneDrive - personal\Network\network.log', 'r+') as LOG:
OUTPUT = LOG.readlines()
for LINE in OUTPUT:
x = re.search(r'\s+name ".*"', LINE)
if x is not None:
print(f'Got match: {x.group()}')
# Otherwise there is not match in the line.
评论