Python 3.x AttributeError:';非类型';对象没有属性';groupdict';
作为python的初学者,我可能会错过一些基础知识。但我在浏览一个项目的代码时,碰巧遇到了这样一个问题: AttributeError:“非类型”对象没有属性“groupdict” 下面是代码的一部分,虽然重新措辞,但这确实会导致相同的问题Python 3.x AttributeError:';非类型';对象没有属性';groupdict';,python,regex,python-3.x,Python,Regex,Python 3.x,作为python的初学者,我可能会错过一些基础知识。但我在浏览一个项目的代码时,碰巧遇到了这样一个问题: AttributeError:“非类型”对象没有属性“groupdict” 下面是代码的一部分,虽然重新措辞,但这确实会导致相同的问题 import re fmt = (r"\+((?P<day>\d+)d)?((?P<hrs>\d+)h)?((?P<min>\d+)m)?" r"((?P<sec>\d+)s)?((?P<
import re
fmt = (r"\+((?P<day>\d+)d)?((?P<hrs>\d+)h)?((?P<min>\d+)m)?"
r"((?P<sec>\d+)s)?((?P<ms>\d+)ms)?$")
p = re.compile(fmt)
match = p.search('Total run time: 9h 34m 9s 901ms realtime, 7h 6m 29s 699ms uptime')
try:
d = match.groupdict()
except IndexError:
print("exception here")
重新导入
fmt=(r“\+((P\d+)d)?((P\d+)h)?((P\d+)m)?”
r“((?P\d+)s)?(?P\d+ms)?$”)
p=重新编译(fmt)
match=p.search('总运行时间:9h 34m 9s 901ms实时,7h 6m 29s 699ms正常运行时间')
尝试:
d=match.groupdict()
除索引器外:
打印(“此处例外”)
这里,match
的计算结果为None
,这在python中是NoneType
。
因此,您得到了错误
您可以设置空检查以避免它,如:
try:
if !(match is None):
d = match.groupdict()
当正则表达式与给定字符串不匹配时,Python中的正则表达式函数返回
None
。因此,在您的情况下,match
是None
,因此调用match.groupdict()
就是尝试不调用任何方法
您应该首先检查match
,然后在访问groupdict()时也不需要捕获任何异常:
在您的特定情况下,表达式无法匹配,因为在最开始时,它正在查找+
符号。而且字符串中没有一个加号,因此匹配肯定会失败。此外,在表达式中,各种时间值之间没有分隔符
试试这个:
>>> expr = re.compile(r"((?P<day>\d+)d)?\s*((?P<hrs>\d+)h)?\s*((?P<min>\d+)m)?\s*((?P<sec>\d+)s)?\s*(?P<ms>\d+)ms")
>>> match = expr.search('Total run time: 9h 34m 9s 901ms realtime, 7h 6m 29s 699ms uptime')
>>> match.groupdict()
{'sec': '9', 'ms': '901', 'hrs': '9', 'day': None, 'min': '34'}
expr=re.compile(r)(((P\d+)d)?\s*((P\d+)h)?\s*((P\d+)m)?\s*((P\d+)s)?\s*((P\d+)ms)
>>>match=expr.search('总运行时间:9h 34m 9s 901ms实时,7h 6m 29s 699ms正常运行时间')
>>>match.groupdict()
{'sec':'9','ms':'901','hrs':'9','day':无,'min':'34'}
以下是理解错误的步骤:
groupdict()
。查看您的代码,变量match
包含“None”match
在哪里初始化?就在前面,使用re.search()
re.search()
返回一个None对象,如果regexp与主题字符串不匹配,这是完全正常的。然后,在不控制其值的情况下调用此None对象上的方法try:
d = match.groupdict()
except IndexError:
print("exception here")
借
由于
re.search
如果失败(),可以返回None
,因此在继续之前,您应该明确检查返回的结果:
if match is not None:
d = match.groupdict()
thanx,我相信这个表达是混乱的
if match is not None:
d = match.groupdict()
else:
print("re.search() returned None")
if match is not None:
d = match.groupdict()