代码之家  ›  专栏  ›  技术社区  ›  ives

python regex“对象没有属性”

  •  8
  • ives  · 技术社区  · 17 年前

    我一直在整理我们需要用新内容更新的页面列表(我们正在切换媒体格式)。在这个过程中,我正在对正确包含新内容的页面进行编目。

    以下是我所做工作的一般概念:

    1. 遍历文件结构并获取文件列表
    2. 对于每个读取到缓冲区的文件,使用regex搜索,匹配特定的标记
    3. 如果匹配,再测试2个regex匹配项
    4. 将结果匹配项(一个或另一个)写入数据库

    在第三个regex模式匹配之前,一切都正常工作,我得到以下信息:

    'NoneType' object has no attribute 'group'

    # only interested in embeded content
    pattern = "(<embed .*?</embed>)"
    
    # matches content pointing to our old root
    pattern2 = 'data="(http://.*?/media/.*?")'
    
    # matches content pointing to our new root
    pattern3 = 'data="(http://.*?/content/.*?")'
    
    matches = re.findall(pattern, filebuffer)
    for match in matches:
        if len(match) > 0:
    
        urla = re.search(pattern2, match)
        if urla.group(1) is not None:
            print filename, urla.group(1)
    
        urlb = re.search(pattern3, match)
        if urlb.group(1) is not None:
            print filename, urlb.group(1)
    

    谢谢您。

    4 回复  |  直到 11 年前
        1
  •  18
  •   oggy    17 年前

    您的异常意味着URLA的值为“无”。由于urla的值由re.search调用确定,因此re.search将返回none。当字符串与模式不匹配时就会发生这种情况。

    所以基本上你应该使用:

    urla = re.search(pattern2, match)
    if urla is not None:
        print filename, urla.group(1)
    

    而不是你现在拥有的。

        2
  •  3
  •   cblab    14 年前

    原因 TypeError 那是 search 或 match 通常返回 MatchObject 或A None . 只有一个有 group 方法。这不是一个 没有 . 所以你需要做的是:

    url = re.search(pattern2, match)
    if url is not None:
        print(filename, url.group(0))
    

    附笔。 PEP-8 建议使用4个空格作为缩进。这不仅是一种意见,也是一种良好的实践。您的代码很难阅读。

        3
  •  2
  •   antonjs    15 年前

    我也有同样的问题。

    使用python2.6,可以通过以下方式解决:

    for match in matches:
     if len(match) > 0:
    
      urla = re.search(pattern2, match)
      try:  
       urla.group(1):
       print filename, urla.group(1)
      excpet:
       print "Problem with",pattern2
    
    
      urlb = re.search(pattern3, match)
      try:
       urlb.group(1)
       print filename, urlb.group(1)
      except:
       print "Problem with",pattern3
    
        4
  •  0
  •   holdenweb    17 年前

    请注意,您的错误假设是 第三的 匹配,实际上是在第二个。这似乎导致了错误的假设,即第二场比赛正在做一些事情使第三场比赛无效,这让你偏离了正轨。