2015-10-06 35 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终端在我设计时测试正则表达式特别有用

相关问题