【问题标题】:python re.findall returns a list of tuples (strings are expected)python re.findall 返回一个元组列表(需要字符串)
【发布时间】:2019-10-03 14:21:01
【问题描述】:

re.findall 返回包含预期字符串和意外字符串的元组列表。

我正在执行函数findtags(text) 以在给定段落text 中查找tags。当我调用re.findall(tags, text) 在文本中查找定义的标签时,它返回一个元组列表。列表中的每个元组都包含我希望它返回的字符串。

函数findtags(text)如下:

import re

def findtags(text):
    parms = '(\w+\s*=\s*"[^"]*"\s*)*'
    tags = '(<\s*\w+\s*' + parms + '\s*/?>)'
    print(re.findall(tags, text))
    return re.findall(tags, text)

testtext1 = """
My favorite website in the world is probably 
<a href="www.udacity.com">Udacity</a>. If you want 
that link to open in a <b>new tab</b> by default, you should
write <a href="www.udacity.com"target="_blank">Udacity</a>
instead!
"""

findtags(testtext1)

预期结果是

['<a href="www.udacity.com">', 
 '<b>', 
 '<a href="www.udacity.com"target="_blank">']

实际结果是

[('<a href="www.udacity.com">', 'href="www.udacity.com"'), 
 ('<b>', ''), 
 ('<a href="www.udacity.com"target="_blank">', 'target="_blank"')]

【问题讨论】:

    标签: python regex python-3.x


    【解决方案1】:

    re.findall 返回一个元组,因为您有两个捕获组,只需使用 ?: 使 params 组不捕获一个即可:

    import re
    
    def findtags(text):
        # make this non capturing group
        parms = '(?:\w+\s*=\s*"[^"]*"\s*)*'
        tags = '(<\s*\w+\s*' + parms + '\s*/?>)'
        print(re.findall(tags, text))
        return re.findall(tags, text)
    
    testtext1 = """
    My favorite website in the world is probably 
    <a href="www.udacity.com">Udacity</a>. If you want 
    that link to open in a <b>new tab</b> by default, you should
    write <a href="www.udacity.com"target="_blank">Udacity</a>
    instead!
    """
    
    findtags(testtext1)
    

    输出:

    ['<a href="www.udacity.com">', '<b>', '<a href="www.udacity.com"target="_blank">']
    

    另一个原因是如果没有捕获组re.findall 将返回匹配的文本:

    # non capturing group
    parms = '(?:\w+\s*=\s*"[^"]*"\s*)*'
    # no group at all
    tags = '<\s*\w+\s*' + parms + '\s*/?>'
    

    【讨论】:

      【解决方案2】:

      根据the docs for re.findall

      如果模式中存在一个或多个组,返回组列表;如果模式有多个组,这将是一个元组列表。结果中包含空匹配项。

      在您的情况下,parms = '(\w+\s*=\s*"[^"]*"\s*)*' 中括号中的内容是重复的组,因此返回可能为空字符串的元组列表。

      【讨论】:

        【解决方案3】:

        看起来您不想返回内部捕获组匹配项,因此改为将其设为非捕获组。

        parms = '(?:\w+\s*=\s*"[^"]*"\s*)*'
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-18
          • 2013-04-09
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多