Python正则表达式查找和替换inp

2024-09-27 19:20:00 发布

您现在位置: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)

输入文件:

^{pr2}$

Tags: inimportretxtfor源代码line精度
3条回答
num_decimal_places = 2
re.sub(r"(\d+)(\.\d{1,num_decimal_places})\d*", r"\1\2", line.rstrip())

\1\2捕获两组括号中的匹配项。这不是四舍五入,但会截断

使用^{},与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对象调用,函数的返回值用作替换字符串。在

以下是稍作修改的版本,以使用捕获的组(用于替换功能)。在

^{pr2}$
import fileinput
import re

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

def changePrecision(matchObj):
    return str(round(float(matchObj.group(0).replace(" ","")),4))

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

我希望这就是你要找的

相关问题 更多 >

    热门问题