python关于芬德尔返回元组列表(应为字符串)

2024-06-28 19:14:49 发布

您现在位置:Python中文网/ 问答频道 /正文

你知道吗关于芬德尔返回一个元组列表,其中包含所需的字符串和意外的内容。你知道吗

我正在执行一个函数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"')]

Tags: 函数字符串textrecomtarget列表www
3条回答

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*/?>'

看起来您不想返回内部捕获组匹配项,所以将其改为非捕获组。你知道吗

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

根据the docs for ^{}

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

在您的例子中,parms = '(\w+\s*=\s*"[^"]*"\s*)*'中括号中的内容是一个重复的组,因此返回一个可能是空字符串的元组列表。你知道吗

相关问题 更多 >