Skip to main content
 首页 » 编程设计

python之对包含在文本文件中的元组执行计算

2024年11月01日9zhenyulu

我有一个包含数据的文本文件。文本文件的片段如下所示:

d1: p,h,t,m= 74.15 18 6 0.1 ign: 0.0003 
 d2: p,h,t,m= 54. 378 -0.14 0.1 ign: 0.0009 
d1: p,h,t,m= 715 8 16 0.1 ign: 0.0003 
 d2: p,h,t,m= 50 78 4 0.1 ign: 0.0009 

(d2 之前有一个空格)。文本文件包含数百行。

我想做的是从 d1 和 d2 中提取数据,例如:

p = 74.15 
t = 18 

等 我通过创建字典来做到这一点。 然后,我想对数据本身进行计算,例如,

p (from d1)* p(d2) + t(from d1) 

并在整个 txt 文件中重复计算。

这是我的代码:

import math 
with open("d.txt") as fp: # Opens the file 
 
    data ={} #final dictionary 
    line = fp.readline() # Read the file's first line 
 
    while line: #continues to end of file 
 
        name, _,cont = line.partition(":")#separates m1 from pt, eta, phi, m =..." 
    #print(cont) 
        numbers, _,ignore = cont.partition("dptinv") #separates dptinv from pt, eta, phi, m =..." 
    #print(numbers) #prints tuple assignment needed 
        keys, _,values = numbers.partition("=") 
    #print(keys) #prints pt, eta, phi, m 
    #print(values) #prints values (all numbers after =) 
        key = [k for k in keys.split(",")] 
        value = [v for v in values.strip().split(" ")] 
    #print(key) #prints pt, eta, phi, m 
    #print(value) 
        thisdict = {} 
        for k, v in zip(key, value): #creating an empty dictionary to fill with keys and values 
            #thisdict[k] = v 
            #print(thisdict) 
        #data[name]=thisdict         
            line = fp.readline()#read next lines 
            thisdict[k] = v 
            data[name]=thisdict 
            print(thisdict) 
 
        #if " m2" in thisdict: 
           #print("Yes") 
 
 
#print(data)        
 
    #mul_p = float(data["m1"][" pt"])*float(data["m1"]["eta"]) 
    m = math.cosh(float(data[" m2"]["eta"])) * float(data["m1"][" pt"]) 
   #m1 = float(data["m1"][" pt"]) * float(2) 
    print(m) 

我的代码是根据我之前关于这个问题的答案组合而成的,但是......

  1. 一个问题是:while 循环读取了整个文件,除了最后两行。

    d1:...

    d2:...

  2. 第二个问题是它似乎没有读取 d2 数据行(或者 line = fp.readline #read next lines 没有做任何事情),因为当我尝试计算 m 时,我得到错误 回溯(最近调用最后):文件“read.py”,第 37 行,在 m = math.cosh(float(data["m2"]["eta"])) * float(data["m1"][ "pt"]) KeyError: 'm2'

我从另一个论坛问过这个问题,我仍在努力理解我编写代码的方式有什么问题。我需要做什么来修复它?非常感谢任何帮助和指导!谢谢!

请您参考如下方法:

你应该尝试重新组织你的阅读过程 并使用更具可读性的数据结构

据我所知, 文本文件中的数据以成对的行分组, 所以我建议的流程是

# do your init outside of the loop 
# 4 lists should have same length  
d1p =[]  
d2p= [] 
d1t= [] 
d2t= [] 
with open("muonsdata.txt") as fp: # Opens the file 
    d1line = fp.readline() # Read one line supposed to have d1  
    d2line = fp.readline() # Read second line supposed to have d2 
    # do more split staff 
    # extract numbers and append to the associate list 
 
for i in range(0..lens(d1p)): 
    m=d1p[i]*d2p[i]+d1t[i]