在Python中将函数传递给re.sub

VPe*_*ric 28 python regex

我有字符串,其中包含一个数字,我试图用他们的单词符号替换这个数字(即3 - > 3).我有一个功能,这样做.现在的问题是找到字符串中的数字,同时保持字符串的其余部分完好无损.为此,我选择使用该re.sub函数,它可以接受"可调用".但是,传递给它的对象是内部的_sre.SRE_Match,我不知道如何处理它.我的函数接受一个数字或其字符串表示.

我应该如何编写一些辅助函数,可以用来桥接re.sub调用我的函数进行所需的处理?或者,有没有更好的方法来做我想要的?

ale*_*cxe 48

您应该调用group()以获取匹配的字符串:

import re

number_mapping = {'1': 'one',
                  '2': 'two',
                  '3': 'three'}
s = "1 testing 2 3"

print re.sub(r'\d', lambda x: number_mapping[x.group()], s)
Run Code Online (Sandbox Code Playgroud)

打印:

one testing two three
Run Code Online (Sandbox Code Playgroud)


glg*_*lgl 18

为了使你的函数适合re.sub,你可以用lambda包装它:

re.sub('pattern', lambda m: myfunction(m.group()), 'text')
Run Code Online (Sandbox Code Playgroud)

  • 从本质上讲,这个问题已经得到了回答.我太晚了...... (3认同)

use*_*003 9

没有 lambda 的解决方案

import re

def convert_func(matchobj):
    m =  matchobj.group(0)
    map = {'7': 'seven',
           '8': 'eight',
           '9': 'nine'}
    return map[m]

line = "7 ate 9"
new_line =  re.sub("[7-9]", convert_func, line)
Run Code Online (Sandbox Code Playgroud)