Python Regex"对象没有属性"

ive*_*ves 8 python regex

我一直在整理我们需要用新内容更新的页面列表(我们正在切换媒体格式).在这个过程中,我正在编写正确拥有新内容的页面.

这是我正在做的一般概念:

  1. 迭代文件结构并获取文件列表
  2. 对于读取缓冲区的每个文件,使用正则表达式搜索匹配特定标记
  3. 如果匹配,则测试2个正则表达式匹配
  4. 将生成的匹配(一个或另一个)写入数据库

一切正常,直到第3个正则表达式模式匹配,我得到以下内容:

'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)
Run Code Online (Sandbox Code Playgroud)

谢谢.

ogg*_*ggy 18

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

所以基本上你应该使用:

urla = re.search(pattern2, match)
if urla is not None:
    print filename, urla.group(1)
Run Code Online (Sandbox Code Playgroud)

而不是你现在拥有的.