将捕获组替换为将捕获组传递给函数的返回值

2024-10-01 15:39:13 发布

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

我试图用将所述捕获组传递给函数的返回值替换特定的捕获组。以下代码使用Python编写:

def translateWord(word):
    ... do some stuff
    return word

def translateSentence(sentence):
    # ([alpha and ']+) [non-alpha]*
    # keep the () part, ignore the rest
    p = re.compile(r"([a-zA-Z']+)[^a-zA-Z]*")

    # find each match, then translate each word and replace
    return p.sub(lambda match: translateWord(match.group(1)), sentence)

此代码将替换整个匹配项,而不是捕获组

不良输出示例:

>>> sentence = This isn't my three-egg omelet.
>>> sentence = translateSentence(sentence)
>>> print(sentence)

Isthayisn'tyayymayeethrayeggyayomeletyay

代码需要输出以下内容:

Isthay isn'tyay ymay eethray-eggyay omeletyay.

translateWord()函数应该只对字符串输入进行操作。我可以测试函数所采用的输入类型,并在此基础上更改行为,但这与目的背道而驰。如何正确地做到这一点


Tags: andthe函数代码alphareturndefmatch
1条回答
网友
1楼 · 发布于 2024-10-01 15:39:13

不管怎样,只要试试:

return p.sub(lambda match: translateWord(match.group(1)), sentence)

看起来您对将什么作为第二个参数传递给re.sub感到困惑:您传递的是实际函数(在本例中是lambda表达式),无需尝试将其嵌入字符串中

但是,如果您只想更改一个组,re方法不会直接支持它-相反,您必须用整个匹配项重新创建一个字符串,替换您要自己更改的组

更简单的方法是将“lambda”函数扩展为另一个多行函数,这将为您带来麻烦。然后,它可以在收到的匹配对象上使用.regs属性来了解组限制(开始和结束),并生成替换字符串:


def replace_group(match):
    sentence = translateWord(match.group(1))
    matched = match.group(0)
    new_sentence = matched[:match.regs[1][0]] + sentence + matched[match.regs[1][1]:] 
    return new_sentence

相关问题 更多 >

    热门问题