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

2024-10-04 03:22:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我的清单如下: 结果=[[0.0,12.053600000000001],[0.01,14.2272],[0.02,15.314000000000002],[0.04,18.5744],[0.05,-18.7720000000000002],[0.67,-1.54]]

我有个档案在.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后面的第二列,即字符串0.00,0.123,0.22,0.456,0.788,0.23在.txt中文件需要分别替换为12.053600000000001、14.2272、15.314000000000002、18.5744、-18.7720000000000002、-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)

请用代码帮助实现这一点。 (编辑:重新导入并声明变量)


Tags: retxt列表ouotwriteelifo2
2条回答

您可以在Jupyter笔记本或Python IDE中遵循以下步骤:

enter image description here

enter image description here

你可以用这个吗?你知道吗

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

相关问题 更多 >