简体   繁体   English

为什么代码抛出“AttributeError: 'NoneType' object has no attribute 'group'”?

[英]Why is the code throwing "AttributeError: 'NoneType' object has no attribute 'group'"?

I tried to run my code however it is throwing "AttributeError: 'NoneType' object has no attribute 'group'" and I can't seem to install regex.我试图运行我的代码,但是它抛出“AttributeError: 'NoneType' object has no attribute 'group'”并且我似乎无法安装正则表达式。 I read that it is built-in but I dont know what to do.我读到它是内置的,但我不知道该怎么做。 here is the code that throws the error:这是引发错误的代码:

while i>0:
    print("Number "+str(i))
    src = str(br.parsed())
    start1 ="¿"
    end1 = "?<"
    result = re.search('%s(.*)%s' % (start1,end1), src).group(1) 
    print(str(result))
    question_index=questions.index(result)
    print("The answer is " + answers[question_index])
    question_form = br.get_form()
    question_form["user_answer"]=answers[question_index]
    br.submit_form(question_form)
    i=i-1 

this line throws the error:这一行抛出错误:

result = re.search('%s(.*)%s' % (start1,end1), src).group(1)

You don't need to "install" the regex module re .您不需要“安装”正则表达式模块re You are correct that it is built-in, you do have it, and it is working fine.你是正确的,它是内置的,你确实拥有它,并且它工作正常。 If you didn't have it, you would have gotten an ImportError when you tried to import it.如果你没有它,当你试图导入它时,你会得到一个ImportError

The problem is that your regex search is not finding any matches, so it is returning None .问题是您的正则表达式搜索没有找到任何匹配项,因此它返回None Then you're immediately trying to access the attribute "group" in None on the same line, which doesn't exist.然后,您立即尝试访问同一行中None中不存在的属性“组”。 Separate out the search from .group(1) , check the return type for None , and proceed only if the return is not None .将搜索从.group(1)分离出来,检查None的返回类型,并且仅当返回不是None时才继续。 If the return value of re.search() is None , then do whatever you want to handle the error - exit, display error message, HCF , whatever.如果re.search()的返回值是None ,那么做任何你想处理错误的事情——退出、显示错误消息、 HCF等等。

Change this:改变这个:

result = re.search('%s(.*)%s' % (start1,end1), src).group(1)

To something like this:对于这样的事情:

result = re.search('%s(.*)%s' % (start1,end1), src)
if result is None:
    print("Error! No matches")
    return # or break, exit, throw exception, whatever

result = result.group(1) # reassign just the group you want to "result"
# carry on with the rest of your loop

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM