Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

regex - Python 3.x AttributeError: 'NoneType' object has no attribute 'groupdict'

Being a beginner in python I might be missing out on some kind of basics. But I was going through one of the codes from a project and happened to face this :

AttributeError: 'NoneType' object has no attribute 'groupdict'

Following is the section of code,re-phrased though,still this does result in the same problem.

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")
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Regular expression functions in Python return None when the regular expression does not match the given string. So in your case, match is None, so calling match.groupdict() is trying to call a method on nothing.

You should check for match first, and then you also don’t need to catch any exception when accessing groupdict():

match = p.search('Total run time: 9h 34m 9s 901ms realtime, 7h 6m 29s 699ms uptime')
if match:
    d = match.groupdict()

In your particular case, the expression cannot match because at the very beginning, it is looking for a + sign. And there is not a single plus sign in your string, so the matching is bound to fail. Also, in the expression, there is no separator beween the various time values.

Try this:

>>> 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'}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...