隐式或未定义的匹配对象

2024-04-28 21:35:39 发布

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

我从使用Python的re模块中学到的是,在使用re函数时,总是创建一个match对象

有人能解释一下这段代码的工作原理吗?我熬不过去了。你知道吗

import re

text = "1 < than 2 > 0 & not 'NULL'"

html_escapes = {'&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                '\'': '&apos;'}


def multiwordreplace(txt, worddict):
    rc = re.compile('|'.join(map(re.escape, worddict)))
    def translate(match):
        return worddict[match.group(0)]
    return rc.sub(translate, txt)

print multiwordreplace(text, html_escapes)

这个match对象来自哪里?你知道吗


Tags: 模块对象textretxtreturndefhtml
2条回答
x = re.compile(a)
x.sub(b, c)

相当于

re.sub(a, b, c)

也就是说,编译的regex apatternb是替换replcstring。你知道吗

在这种情况下,repl函数translate。从the docs

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

match参数由re.substring中的每个匹配项提供,函数返回worddict中的适当替换项以替换为txt。你知道吗

你也可以这样写:

return rc.sub(lambda match: worddict[match.group(0)], txt)

我假设你的意思是match在:

def translate(match):
    return worddict[match.group(0)]

起源于。Python支持函数式编程的概念,其中可以将函数作为参数传递。你知道吗

如果你这样称呼re.sub为:

rc.sub(translate, txt)

translate是一个函数。而rc.sub所做的就是寻找匹配项。每次匹配,都会用生成的参数调用函数。结果是该函数的替代。你知道吗

另一个例子是map函数:

def map(f, lst):
    result = []
    for x in lst:
        result.append(f(x))
    return result

因此,所发生的是用函数调用map。然后迭代lst,对于每个元素x,用x调用f。结果将附加到列表中。你知道吗

因此,您不必传递带有参数的translate来获得值,您可以传递函数,这样另一个函数就可以用几个(不同)值本身调用该函数。你知道吗

相关问题 更多 >