Python正则表达式在原处查找和替换

用户名

我有一个片段,可以找到像1.321234123这样的浮点数我想摆脱一些精度,使1.3212但是我该如何访问找到的匹配项,将其转换并替换呢?

Python资料来源:

import fileinput
import re

myfile = open("inputRegex.txt", "r")

for line in myfile:
    line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?", "foundValue", line.rstrip())
    print(line)

输入文件:

4.2abc -4.5 abc - 1.321234123 abc + .1e10 abc . abc 1.01e-2 abc

   1.01e-.2 abc 123 abc .123
虚假的

使用fileinput.FileInput,用inplace=True打印的行将用作每行的替换字符串。

myfile = fileinput.FileInput("inputRegex.txt", inplace=True)

for line in myfile:
    line = re.sub(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
                  "foundValue",
                  line.rstrip())
    print(line)

更新

re.sub可以接受替代功能。它将与match对象一起调用,并且该函数的返回值用作替换字符串。

以下是使用捕获的组(用于替换功能)的略微修改版本。

line = re.sub(r"([+-]? *)(\d+(?:\.\d*)?|\.\d+)([eE][+-]?\d+)?",
              lambda m: m.group(1) + re.sub('(\..{4}).*', r'\1', m.group(2)) + (m.group(3) or ''),
              line.rstrip())

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章