如何将round()放入正则表达式中?

2024-10-03 17:16:49 发布

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

我有一个巨大的.json文件,它包含多个信息,我只需要在“heightroof”参数中舍入数字

我正在使用Regex,我有heightroof": "(.*?)"表达式来找到我需要的东西。我可以搜索“heightroof”:“(.*?”)并替换为“height”:\1在Emeditor中使用regex,这将使它工作,但我不能对数字进行舍入。但我还需要对“heightroof”之后的数字进行舍入

而不是这样:

 "heightroof": "21.3423423",

我需要这个:

 "height": 21,

请帮我把数字四舍五入


Tags: 文件信息json参数表达式数字regexheight
2条回答

我想您需要回电话来做这件事
使用re.sub('rx',lambda m => {} )形式

接收

"(height)roof"\s*:\s*"(\d+(?:\.\d*)?)",

然后在回调函数中,将m[2]转换为一个float,四舍五入,然后取整数部分
使其成为字符串,然后使用字符串部分"+m[1]+":"+round+",
等等

sin是正确的,因为您需要一个回调函数

import re

s = '"heightroof": "21.3423423"'

def repl(m):
    return '"height": ' + str(round(float(m.group(1))))

re.sub(r'"heightroof": "([^"]+)"', repl, s)

'"height": 21'

相关问题 更多 >