如何转换数据文件格式或直接用matplotlib/gnuplot绘制非标准数据?
数据格式转换与直接绘图方案
原始数据格式
0.1 Analytic value = 340.347685734 Approximated value = 332.45634555 -- 0.2 Analytic value = 340.936745872 Approximated value = 332.57893789 -- 0.3 ... and so on
目标转换格式
0.1 340.347685734 332.45634555 0.2 340.936745872 332.57893789 0.3 ... and so on
1. AWK最优转换方案
一行命令即可高效完成格式转换,无需额外依赖:
awk ' NR%4==1 { param=$0 } NR%4==2 { split($0, arr, "="); analytic=arr[2] } NR%4==3 { split($0, arr, "="); approx=arr[2]; print param, analytic, approx } ' myFile.dat > newFile.dat
逻辑说明:
NR%4==1:每4行的第1行是输入参数,暂存到变量paramNR%4==2:第2行提取Analytic value的数值部分NR%4==3:第3行提取Approximated value的数值部分,同时拼接三个值并输出- 自动跳过第4行的分隔符
--
2. GNUPLOT直接绘图(无需生成中间文件)
如果不想转换格式,可直接在gnuplot中通过调用awk处理数据并绘图:
plot '< awk ''NR%4==1{p=$0} NR%4==2{split($0,a,"=");an=a[2]} NR%4==3{split($0,b,"=");ap=b[2];print p,an,ap}'' myFile.dat' \ using 1:2 title 'Analytic Value' with lines, \ '' using 1:3 title 'Approximated Value' with lines
也可以用gnuplot原生语法逐行解析数据:
set datafile separator "\n" param = 0.0 analytic = 0.0 approx = 0.0 plot 'myFile.dat' using ( \ if (strcol(1) !~ /--/) { \ if (strcol(1) ~ /^[0-9]/) { param = real(strcol(1)) } \ else if (strcol(1) ~ /Analytic/) { analytic = real(substr(strcol(1), index(strcol(1),"=")+1)) } \ else if (strcol(1) ~ /Approximated/) { approx = real(substr(strcol(1), index(strcol(1),"=")+1)) } \ } \ param : analytic ) title 'Analytic' with lines, \ '' using (param : approx) title 'Approximated' with lines
3. 修正后的Python处理方案
你之前的代码报错是因为split是方法,需要加括号调用split()而非直接用split[-1]。修正后的高效代码如下:
with open("myFile.dat", 'r') as f_in, open("newFile.dat", 'w') as f_out: while True: # 读取输入参数行,判断文件是否结束 param_line = f_in.readline() if not param_line: break param = param_line.strip() # 提取解析值 analytic = f_in.readline().strip().split("=")[-1].strip() # 提取近似值 approx = f_in.readline().strip().split("=")[-1].strip() # 跳过分隔符行 f_in.readline() # 写入转换后的行 f_out.write(f"{param} {analytic} {approx}\n")
优化点:
- 用
with语句自动管理文件句柄,避免资源泄漏 - 无需固定循环次数,自动处理到文件结束
- 用
strip()去除多余空格和换行符,保证格式整洁
内容的提问来源于stack exchange,提问作者AbdulMuhaymin
相关产品推荐
相关产品推荐

