我尝试编写一个python代码来从输入中提取DVDL值。这是截断的输入。
A V E R A G E S O V E R 50000 S T E P S
NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 300.05 PRESS = -70.0
Etot = -89575.9555 EKtot = 23331.1725 EPtot = -112907.1281
BOND = 759.8213 ANGLE = 2120.6039 DIHED = 4231.4019
1-4 NB = 940.8403 1-4 EEL = 12588.1950 VDWAALS = 13690.9435
EELEC = -147238.9339 EHBOND = 0.0000 RESTRAINT = 0.0000
DV/DL = 13.0462
EKCMT = 10212.3016 VIRIAL = 10891.5181 VOLUME = 416404.8626
Density = 0.9411
Ewald error estimate: 0.6036E-04
R M S F L U C T U A T I O N S
NSTEP = 50000 TIME(PS) = 300.000 TEMP(K) = 1.49 PRESS = 129.9
Etot = 727.7890 EKtot = 115.7534 EPtot = 718.8344
BOND = 23.1328 ANGLE = 36.1180 DIHED = 19.9971
1-4 NB = 12.7636 1-4 EEL = 37.3848 VDWAALS = 145.7213
EELEC = 739.4128 EHBOND = 0.0000 RESTRAINT = 0.0000
DV/DL = 3.7510
EKCMT = 76.6138 VIRIAL = 1195.5824 VOLUME = 43181.7604
Density = 0.0891
Ewald error estimate: 0.4462E-04
这是脚本。基本上我们在输入中有很多DVDL(不在上面的截断输入中),我们只想要最后两个。所以我们把所有这些都读成一个列表,只得到最后两个。最后,我们将列表中的最后两个DVDL写入csv文件。欲望输出是
13.0462,3.7510
但是,以下脚本(python 2.7)将带来这样的输出。任何古茹都可以开导吗?感谢。
13.0462 “” 3.7510 “”
这是脚本:
import os
import csv
DVDL=[]
filename="input.out"
file=open(filename,'r')
with open("out.csv",'wb') as outfile: # define output name
line=file.readlines()
for a in line:
if ' DV/DL =' in a:
DVDL.append(line[line.index(a)].split(' ')[1]) # Extract DVDL number
print DVDL[-2:] # We only need the last two DVDL
yeeha="".join(str(a) for a in DVDL[-2:])
print yeeha
writer = csv.writer(outfile, delimiter=',',lineterminator='\n')#Output the list into a csv file called "outfile"
writer.writerows(yeeha)
答案 0 :(得分:1)
由于提出方法的评论者没有机会为此概述一些代码,这就是我建议的方式(编辑以允许可选的带有可选指数的带符号浮点数),如对{的回答所建议的那样{3}}):
import re,sys
pat = re.compile("DV/DL += +([+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
values = []
for line in open("input.out","r"):
m = pat.search(line)
if m:
values.append(m.group(1))
outfile = open("out.csv","w")
outfile.write(",".join(values[-2:]))
运行此脚本:
$ cat out.csv
13.0462,3.7510
在这种情况下我没有使用csv
模块,因为对于像这样的简单输出文件来说,它并不是必需的。但是,在脚本中添加以下行将使用csv
将相同的数据写入out1.csv
:
import csv
writer = csv.writer(open("out1.csv","w"))
writer.writerow(values[-2:])