在正则表达式中应用 lambda 函数

Applying lambda funtion in Regex

我有一个包含文本和数值的句子。我想对数字进行分解。

s = "the quick brown fox jumps over the lazy dog 123.456"

预期结果:

"the quick brown fox jumps over the lazy dog 1_hundreds 2_tens 3_ones 4_tenths 5_hundredths 6_thousandths"

我成功应用了分解函数:

然后,我在正则表达式中应用 lambda 函数。不幸的是,我得到如下错误。请帮助我。谢谢!

全部代码如下:

vital_sign_values = [('thousands', 1000), ('hundreds', 100), ('tens', 10), 
                     ('fives', 5), ('ones', 1), ('tenths', 0.1), ('hundredths', 0.01), ('thousandths', 0.001)]


def decoding_digits(num):

    num = float(num)

    num = int(num * 1000)

    num = float(num) / 1000

    output_dict = {}
    for place, value in vital_sign_values:
        output_dict[place] = num // value
        num = num % value
    
    result = [str(int(v))+"_"+k for k,v in output_dict.items() if v!=0]
    
    return(result)

numeric_decode = decoding_digits(123.456)

import re

from functools import partial

s = "the quick brown fox jumps over the lazy dog 123.456"
 
vital_number = re.compile(r"([0-9]+([,.])+([0-9]+)?)")

result = vital_number.sub(partial(decoding_digits), s)

您的问题是 re.sub 将匹配对象传递给回调,而您的 decoding_digits 函数需要一个字符串。您可以使用 lambda 函数从匹配对象传递匹配的字符串,例如

result = vital_number.sub(lambda m:decoding_digits(m.group()), s)

此外,decoding_digits returns 一个列表,而不是一个字符串。您可以通过更改

来解决这个问题
return(result)

return ' '.join(result)

最终代码:

vital_sign_values = [('thousands', 1000), ('hundreds', 100), ('tens', 10), 
                     ('fives', 5), ('ones', 1), ('tenths', 0.1), ('hundredths', 0.01), ('thousandths', 0.001)]

def decoding_digits(num):
    num = float(num)
    num = int(num * 1000)
    num = float(num) / 1000

    output_dict = {}
    for place, value in vital_sign_values:
        output_dict[place] = num // value
        num = num % value
    
    result = [str(int(v))+"_"+k for k,v in output_dict.items() if v!=0]
    return ' '.join(result)

import re

s = "the quick brown fox jumps over the lazy dog 123.456"
 
vital_number = re.compile(r"([0-9]+([,.])+([0-9]+)?)")

result = vital_number.sub(lambda m:decoding_digits(m.group()), s)
print(result)

输出:

the quick brown fox jumps over the lazy dog 1_hundreds 2_tens 3_ones 4_tenths 5_hundredths 6_thousandths