简体   繁体   中英

Python regex find and replace inplace

I have a snippet that finds floating point numbers like 1.321234123 . I would like to get rid of some precision and make 1.3212 out of it. But how can i access the found match, convert it and replace it?

Python Source:

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)

The Input File:

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

   1.01e-.2 abc 123 abc .123

Use fileinput.FileInput , with inplace=True . printed line will be used as a replacement string for each line.

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)

UPDATE

re.sub can accept a function as replacement. It will be called with match object and the return value of the function is used as a replacement string.

The following is slightly modified version to use captured groups (to use in replacement function).

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())
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

I hope this is what you are looking for

num_decimal_places = 2
re.sub(r"(\d+)(\.\d{1,num_decimal_places})\d*", r"\1\2", line.rstrip())

\\1\\2 captures the matches in the two sets of parentheses. This doesn't round, but it will truncate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM