【问题标题】:Why is the code throwing "AttributeError: 'NoneType' object has no attribute 'group'"?为什么代码会抛出“AttributeError: 'NoneType' object has no attribute 'group'”?
【发布时间】:2018-05-25 15:33:50
【问题描述】:

我试图运行我的代码,但是它抛出“AttributeError: 'NoneType' object has no attribute 'group'”并且我似乎无法安装正则表达式。我读到它是内置的,但我不知道该怎么做。这是引发错误的代码:

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 

这行抛出错误:

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

【问题讨论】:

    标签: python attributeerror nonetype


    【解决方案1】:

    您不需要“安装”正则表达式模块re。您是正确的,它是内置的,您确实拥有它,并且工作正常。如果你没有它,当你尝试导入它时,你会得到一个ImportError

    问题是您的正则表达式搜索未找到任何匹配项,因此它返回None。然后您立即尝试访问同一行上None 中的属性“组”,该属性不存在。将搜索与.group(1) 分开,检查None 的返回类型,仅当返回不是None 时才继续。如果re.search() 的返回值为None,则执行任何您想要处理错误的操作 - 退出、显示错误消息、HCF 等等。

    改变这个:

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

    这样的:

    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
    

    【讨论】:

      猜你喜欢
      • 2023-01-16
      • 1970-01-01
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 2020-05-26
      • 2017-10-20
      相关资源
      最近更新 更多