我有一个巨大的.json文件,其中包含多个信息,我只需要在参数"heightroof“中舍入数字。
我使用正则表达式和heightroof": "(.*?)"表达式来查找我需要的内容。我可以搜索"heightroof":"(.*?)“并替换为"height":\1在Emeditor中使用正则表达式可以使其工作,但我不能对numbers.But进行舍入我还需要在"heightroof“之后对数字进行舍入。
而不是这样:
"heightroof": "21.3423423",我需要这个:
"height": 21,请帮我把这些数字取个整数。
发布于 2019-08-15 05:48:40
我认为你需要一个回调来做这件事。
使用re.sub('rx',lambda m => {} )表单
Rx
"(height)roof"\s*:\s*"(\d+(?:\.\d*)?)",
然后在回调中将m[2]转换为浮点型,向上舍入,然后取整数部分
将其转换为字符串,然后使用字符串parts " + m1 + ":" + round + ",返回
等等。
发布于 2019-08-15 05:54:16
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'https://stackoverflow.com/questions/57502234
复制相似问题