属性错误:'NoneType'对象在尝试循环'groups'没有属性



我使用正则表达式来剥离数据。

如果我硬编码数据并将其与正则表达式匹配,则可以正常工作。但是,如果我对每个循环使用a,将循环变量传递给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",那么它工作良好。

谁能告诉我如何在循环中正确地迭代它以获得值并避免错误

我不太明白你想用这个循环做什么,但我会回答为什么会出现这个错误。

看起来你试图匹配一个字符和那个正则表达式。

y.append(str(c))

y追加一个字符,然后用

循环每个字符
for x in y:

regex 永远不会匹配1个字符,因为它至少需要8个字符才能匹配。

re.match()实际上不匹配字符串时, object has no attribute 'groups' ,这是您得到的错误。

如果您的数据的结构使您不希望每次都找到匹配,而只想收集匹配。您可以分离内联循环来构建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)

如果你的数据应该总是找到一些匹配,那么你的正则表达式格式不正确,你需要调试。(我发现python终端在测试正则表达式时特别有用,当我设计它们

最新更新