首页 > 解决方案 > Replace floats with ints in text files

问题描述

I want to find and replace floats with integers in several text files.
There is one float value per text file which I want to convert. It is always after a specific keyword and has to be multiplied by 10.000.
e.g. the float 1.5 should be turned into the integer 15.000
The other floats after 1.5 don't have to be changed though

def edit(file):
    with open(file, 'r') as f:
        filedata = f.read()
        for line in filedata:
           if "keyword" in line:
              filedata = filedata.replace(re.search(r"\d+\.\d+", line).group(), str(10000*re.search(r"\d+\.\d+", line).group()))
    with open(file, 'w') as f:
        f.write(filedata)

I was trying to replace the the float using a regex. But this doesn't work

EXAMPLE FILE EXTRACT

abcdef 178 211 208 220    
ghijkl 0 0 0 0  
keyword 1.50 1.63 1.56 1.45

标签: pythontexttype-conversioninteger

解决方案


当您发现自己在循环中使用正则表达式时,您应该在循环之外编译它。

接下来,如果要替换一行中的值,则不应在整个文件中搜索它。

最后,您必须将字符串转换为数字类型才能对其进行操作。如果你不这样做,你只会重复字符串('10' * 2is '1010'not 20nor '20'

这是您的代码的可能改进:

def edit(file):
    with open(file, 'r') as f:
        rx = re.compile(r"\d+\.\d+")        # compile the regex only once
        filedata = f.readlines()            # get a list of the lines of the file
        for i, line in enumerate(filedata): # and enumerate them
            if "keyword" in line:
                val = re.search(r"\d+\.\d+", line).group()   # split the complex line
                newval = str(int(float(val) * 10000))
                filedata[i] = line.replace(val, newval)      # replace only the current line
                break                                        # no need to proceed further
    with open(file, 'w') as f:
        f.write(filedata)

推荐阅读