2015-10-06 79 views
0

我正在使用正則表達式去除數據。AttributeError:'NoneType'對象沒有屬性'組'嘗試循環

如果我對數據進行硬編碼並將其與正則表達式進行匹配,它可以正常工作。但是,如果使用一個For Each循環,循環變量傳遞給re.match(),我得到以下錯誤:

 re.VERBOSE 
AttributeError: 'NoneType' object has no attribute 'groups'** 

我的代碼:

trs = soup.findAll("tr") 
for tr in trs: 
    c = unicodedata.normalize('NFKD', tr.text) 
    y.append(str(c)) 
for x in y: 
    #data1 = "Ambala 1.2 Onion 1200 2000 1500" 
    x1 = ([c.strip() for c in re.match(r""" 
     (?P<market>[^0-9]+) 
     (?P<arrivals>[^ ]+) 
     (?P<variety>[^0-9]+) 
     (?P<min>[0-9]+) 
     \ (?P<max>[0-9]+) 
     \ (?P<modal>[0-9]+)""", 
     x, 
     re.VERBOSE 
    ).groups()]) 

如果我設置data1 = "Ambala 1.2 Onion 1200 2000 1500",然後正常工作。

誰能告訴我如何在循環中正確地迭代它以獲取值並避免錯誤。

+0

你能指定你想要做什麼嗎?爲什麼你要循環每個字符? – Mariano

回答

0

我不太明白你想用循環做什麼,但我會回答爲什麼會引發這個錯誤。

它看起來像你試圖匹配一個字符與該正則表達式。

y.append(str(c)) 

追加字符y,然後循環使用

for x in y: 

該正則表達式的每個字符永遠比不上1個字符,因爲它需要至少8個字符相匹配。

re.match()與字符串不匹配時,object has no attribute 'groups',這是您得到的錯誤。

0

如果您的數據的結構使您不希望每次都找到匹配項,而只想收集匹配項。您可以分開你的內聯環建x1和檢查

x1 = [] 
for x in y: 
    tmp = re.match(r""" ...""",x) 
    try: 
     x1 = ([c.strip() for c in tmp.groups]) 
    except AttributeError: 
     print "no match found in x:{}".format(x) 

或與if語句

... 
    if tmp is not None: 
     x1 = ([c.strip() for c in tmp.group]) 
    else: 
     print "no match found in x:{}".format(x) 

如果你的數據應該找到一些比賽總是那麼你的正則表達式的格式不正確,你需要調試那。 (我發現ipython終端在我設計時測試正則表達式特別有用