2017-05-22 1 views
1

if 문과 함께 파이썬의 정규식을 사용하고 있습니다. 일치 항목이 None 인 경우 else 절로 가야합니다. 그러나이 오류를 보여줍니다파이썬 : if 문 "if not none"처리

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

스크립트는 다음과 같습니다

import string 
chars = re.escape(string.punctuation) 
sub='FW: Re: 29699' 
if re.search("^FW: (\w{10})",sub).group(1) is not None : 
    d=re.search("^FW: (\w{10})",sub).group(1) 
else: 
    a=re.sub(r'['+chars+']', ' ',sub) 
    d='_'.join(a.split()) 

모든 도움이 큰 도움이됩니다!

+1

당신은'is None'이 아니라'is not'라고 썼습니다. – spies006

+0

첫 번째 오류는 가져 오기 다시입니다 – bigbounty

+0

그 다음에도 작동하지 않습니다 –

답변

3

문제는 다음과 같습니다. 검색에서 아무 것도 찾지 못하면 None을 반환합니다. 귀하의 코드 금액 인 None.group(1)을 수행 할 수 없습니다. 대신 검색 결과None 인 지 검색 결과의 첫 번째 그룹이 아닌지 확인하십시오.

import re 
import string 

chars = re.escape(string.punctuation) 
sub='FW: Re: 29699' 
search_result = re.search(r"^FW: (\w{10})", sub) 

if search_result is not None: 
    d = search_result.group(1) 
else: 
    a = re.sub(r'['+chars+']', ' ', sub) 
    d = '_'.join(a.split()) 

print(d) 
# FW_RE_29699 
+0

그건 논리적입니다, 감사합니다! –