[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
返回列表 发帖

[问题求助] Python如何按列取出txt文件中的数据?

本帖最后由 Blakelee 于 2021-10-28 14:17 编辑

求助,有一个数据文件格式(data.txt)如下,想按列取出数据:a=[600.00, 607.00, 614.00,......,684.00],dio=[0.38072, 0.37969,......,0.36806], ksp=[0.02269, 0.02270,......,0.02291], mu=[0.02519, 0.02519,......,0.02519], g=[0.37565, 0.37705,......,0.39272], ru=[0.00787, 0.00787,......,0.00787],  ky=[ 0.04390, 0.04330,......,0.03659], 谢谢!
From zero to one!

好的,谢谢!
From zero to one!

TOP

回复 3# Blakelee
格式和你给的例子文本可能不同。你先看明白了,再改改应该不难呀

TOP

回复 2# cfwyy77_bat

运行报错了
From zero to one!

TOP

  1. file = "data.txt"
  2. g={}
  3. def main():
  4.     local={"a": []}
  5.     with open(file,"r",encoding="utf-8") as f:
  6.         for line in f:
  7.             row = line.strip('\n')[2:-3]  #去回车及首尾多余{},
  8.             if row:
  9.                 items = row.split('}, {')
  10.                 local["a"].append(float(items[0].split(',')[1]))  #第1列
  11.                 for i in range(1,len(items)):  #处理第2~8列
  12.                     item = items[i].split(',')
  13.                     key = item[0].strip('"')
  14.                     value = float(item[1])
  15.                     if key not in local:
  16.                         exec(f"{key}=[]",g,local)
  17.                     exec(f"{key}.append({value})",g,local)
  18.    
  19.     for k,v in local.items():
  20.         print(f"{k} = {v}")
  21. if __name__ == "__main__":
  22.     main()
复制代码
结果:
  1. a = [600.0, 607.0, 614.0, 621.0, 628.0, 635.0, 642.0, 649.0, 656.0, 663.0, 670.0, 677.0, 684.0]
  2. dio = [0.38072, 0.37969, 0.37865, 0.37761, 0.37656, 0.3755, 0.37445, 0.37338, 0.37232, 0.37125, 0.37019, 0.36913, 0.36806]
  3. ksp = [0.02269, 0.0227, 0.02272, 0.02273, 0.02275, 0.02276, 0.02278, 0.0228, 0.02282, 0.02284, 0.02286, 0.02288, 0.02291]
  4. mu = [0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519, 0.02519]
  5. g = [0.37565, 0.37705, 0.37846, 0.37988, 0.3813, 0.38272, 0.38415, 0.38558, 0.38701, 0.38844, 0.38987, 0.3913, 0.39272]
  6. ru = [0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787, 0.00787]
  7. q = [0.14396, 0.14419, 0.14441, 0.14464, 0.14487, 0.14509, 0.14532, 0.14554, 0.14577, 0.14599, 0.14621, 0.14644, 0.14666]
  8. ky = [0.0439, 0.0433, 0.04269, 0.04208, 0.04147, 0.04086, 0.04024, 0.03963, 0.03902, 0.03841, 0.0378, 0.03719, 0.03659]
复制代码
1

评分人数

TOP

返回列表