用列表值替换文件中的字符串

时间:2018-12-16 08:30:52

标签: python string file arraylist replace

我的列表为: 结果= [[0.0,12.053600000000001],[0.01,14.2272],[0.02,15.314000000000002],[0.04,18.5744],[0.05,-18.772000000000002],[0.67,-1.54]]

我在in.txt文件中包含以下值:

NPTH 6
THTIM 
  0.0  0.00  0.001  -1.22
  0.01  0.123 0.550  -1.44
  0.02  0.22  0.440  -1.55
  0.04  0.456  0.220  -1.88
  0.05  0.788  0.005  1.9
  0.67  0.23  0.340   0.2

NPPD 4
1.0 5.0 8.0
1.0 4.0 2.0
2.0 5.0 2.0
4.0 5.0 2.0    

THTIM 5
2.0 1.0
1.0 2.0
1.0 1.0

我需要用结果列表中每个列表中的第二个参数替换THTIM之后的第二列,即in.txt文件中的字符串0.00,0.123,0.22,0.456,0.788,0.23需要替换为12.053600000000001,14.2272,15.314000000000002, 18.5744,-18.772000000000002,-1.54。 即我需要我的输出为

NPTH 6
THTIM 
0.00  12.053600000000001  0.001  -1.22
0.01  14.2272             0.550  -1.44
0.02  15.314000000000002  0.440  -1.55
0.04  18.5744             0.220  -1.88
0.05  -18.772000000000002 0.005  1.9
0.67  -1.54              0.340   0.2    

NPPD 4
1.0 5.0 8.0
1.0 4.0 2.0
2.0 5.0 2.0
4.0 5.0 2.0

THTIM 5
2.0 1.0
1.0 2.0
1.0 1.0

我尝试过的是:

f3=open("in.txt" ,'r')
import re
result=[[0.0, 12.053600000000001], [0.01, 14.2272], [0.02,15.314000000000002], [0.04, 18.5744], [0.05, -18.772000000000002], [0.67, -1.54]]
o2=open("out.txt" ,'w')
thtm2Cnt=0
thtm2Flag=0
for ot in f3.readlines():
    ou=ot
    print(ot)
    if re.match('NPTH',ou):

        o2.write(ou)
        strplt =ou.split()
        cnt=int(strplt[1])
    elif re.match('THTIM',ou):
        thtm2Flag=1

        o2.write(ou)
    elif thtm2Flag==1:
        if thtm2Cnt<=cnt-1:
            strplt=ou.split()
            ou = strplt[0] + "\t" +  "\t" + strplt[2] + "\t" + strplt[3] + " \n        "
            o2.write(ou)
            thtm2Cnt+=1
        elif thtm2Cnt==cnt:
            thtm2Cnt=0
            thtm2Flag=0
            o2.write(ou)
    else:
        o2.write(ou)

请帮助提供代码以实现此目的。 (编辑:导入re并声明变量)

2 个答案:

答案 0 :(得分:1)

您可以在Jupyter笔记本中或在Python IDE中进行以下操作:

enter image description here

enter image description here

答案 1 :(得分:0)

您想使用这个吗?

import re
replace_column=["12.053600000000001", "14.2272","15.314000000000002", "18.5744", "-18.772000000000002", "-1.54"]

def process(part) :
    if re.search("NPTH \d",part) and re.search("THTIM",part):
        lines = part.split("\n")
        grid = [line.split() for line in lines[2:]]
        result = []
        for idx, row in enumerate(grid):
            newrow = []
            for index, cell in enumerate(row):
                if index == 1:
                    newrow = newrow + [replace_column[idx]]
                else:
                    newrow = newrow + [cell]
            result = result + [newrow]
        return "\n".join(lines[:2] + ["\t".join(row) for row in result])
    else:
        return part

fr=open('in.txt','r')
fw=open('out.txt','w')
f = fr.read()
fr.close()
parts = f.split("\n\n")
fw.write("\n\n".join([process(part) for part in parts]))