![](/img/trans.png)
[英]AttributeError: 'NoneType' object has no attribute 'group' ,
[英]Why is the code throwing "AttributeError: 'NoneType' object has no attribute 'group'"?
我試圖運行我的代碼,但是它拋出“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)
您不需要“安裝”正則表達式模塊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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.