Reading a Tuple Assignment (e.g.written as such d1: p, m, h, = 20, 15, 22) from a Text File and Performing Calculations with Each Variable (e.g. p*h)

时光怂恿深爱的人放手 提交于 2020-01-04 06:09:02

问题


I'm a reading a text file with several hundred lines of data in python. The text file contains data written as a tuple assignment. For example, the data looks exactly like this in the text file:

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

How can I separate the data as such:

p = 20

t = 15

etc. Then, how can I perform calculations on the tuple assignment? For example calculate:
p*p = 20*15?

I am not sure if I should convert the tuple assignment to an array. But I was not successful. In addition, I do not know how to get rid of the d1 and d2: which is there to identify which data set I am looking at

I have read the data and picked out the lines that have the data, (ignoring the First Set line and of Data Given as line)

The results that I need would be:

p (from first set of data d1)*p(from first set of data d2) = 20*15 = 300

p (from second set of data d1)*p(from second set of data d2) = 12*5 = 60

I believe I would need to do this over some kind of loop so that I can separate the data in all the lines in the file.

I would appreciate any help on this! I couldn't find anything pertaining to my question. I would only find how to deal with tuples in the simplest manner but nothing on how to extract variables and performing calculations on a tuple assignment contained in a text file.

EDIT:

After looking at the answer given for this question given by @JArunMani, I went back to try to see if I can understand each line of code. I understand that we need to create a dictionary that fills in the respective values for p, q, etc... When I try to rewrite the code to how I understand it, I have:

with open("d.txt") as fp: # Opens the file 
  # The database kinda thing here
 line = fp.readline() # Read the file's first line
 number, _,cont = line.partition(":")#separates m1 from p, m, h, n =..."
 print(cont)
 data, _,ignore = cont.partition("int") #separates int from p, m, h, n =..."
 print(data) #prints tuple assignment needed
 keys, _,values = data.partition("=")
 print(keys) #prints p, m, h, n
 print(values) #prints values (all numbers after =)
 thisdict = {} #creating an empty dictionary to fill with keys and values
 thisdict[keys] = values
 print(thisdict)
 if "m" in thisdict:
     print("Yes")

print(thisdict) gives me the Output: {' p,m,h,n': ' 76 6818 2.2 1 '}

However, if "m" in thisdict: did not print anything. I do not understand why m is not in the dictionary, yet print(thisdict) shows that thisdict = {} has been filled. Also, is it necessary to add the for loop in the answer given below?

Thank you.

EDIT 2

I am now trying my second attempt to this problem. I combining both answers to write the code since I using what I understand from each code: def DataExtract(self): with open("muonsdata.txt") as fp: # Opens the file

   line = fp.readline() # Read the file's first line
   number, _,cont = line.partition(":")#separates m1 from pt, eta, phi, m =..."
   print(cont)
   data, _,ignore = cont.partition("dptinv") #separates dptinv from pt, eta, phi, m =..."
   print(data) #prints tuple assignment needed
   keys, _,values = data.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)
   print(value)
   thisdict = {}
   data = {}
   for k, v in zip(key, value): #creating an empty dictionary to fill with keys and values
         thisdict[k] = v
         print(thisdict)
         if "m" in thisdict:

             print("Yes")


x = DataExtract("C:/Users/username/Desktop/data.txt")
mul_p = x['m1']['p'] * x['d2']['p']
print(mul_p)

However, this gives me the error: Traceback (most recent call last): File "read.py", line 29, in mul_p = x['d1']['p'] * x['d2']['p'] TypeError: 'NoneType' object is not subscriptable

EDIT 3

I have the code made from a combination of answers 1 and 2, BUT... the only thing is that I have the code written and working but why doesn't the while loop go on until we reach the end of the file. I only get one answer from the calculating the values from the first two lines, but what about the remaining lines? Also, it seems like it is not reading the d2 data lines (or the line = fp.readline is not doing anything), because when I try to calculate m , I get the error Traceback (most recent call last): File "read.py", line 37, in m = math.cosh(float(data[" m2"]["eta"])) * float(data["m1"][" pt"]) KeyError: ' m2'

Here is my code that I have:

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 d1 from p, m, h, t =..."
        #print(cont)
        numbers, _,ignore = cont.partition("ign") #separates ign from p, m, h, t =..."
        #print(numbers) #prints tuple assignment needed
        keys, _,values = numbers.partition("=")
        #print(keys) #prints p, m, h, t
        #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, not working I think
            thisdict[k] = v
            data[name]=thisdict
            print(thisdict)

        #if " m2" in thisdict:
           #print("Yes")

       #print(data)       

#mul_p = float(data["d1"][" p"])*float(data["d1"]["m"])
    m = math.cosh(float(data[" d2"]["m"])) * float(data["m1"][" p"])
#m1 = float(data["d1"][" p"]) * float(2)
    print(m)

#print(mul_p)

If I replace the d2's with d1 the code runs fine, except it skips the last d1. I do not know what I am doing wrong. Would appreciate any input or guidance.


回答1:


So the following function returns a dictionary with values of 'p', 'q' and other variables. But I leave it to you to find out how to multiply or perform operations on them ^^

def DataExtract(path): # 'path' is the path to the data file 
    fp = open(path) # Opens the file 
    data = {} # The database kinda thing here
    line = fp.readline() # Read the file's first line
    while line: # This goes on till we reach end of file (EOF)
        name, _, cont = line.partition(":") # So this gives, 'd1', ':', 'p, q, ...'
        keys, _, values = cont.partition("=") # Now we split the text into RHS and LHS
        keys = keys.split(",") # Split the variables by ',' as separator
        values = values.split(",") # Split the values
        temp_d = {} # Dict for variables
        for i in range(len(keys)):
            key = keys[i].strip() # Get the item at the index and remove left-right spaces
            val = values[i].strip() # Same
            temp_d[key] = float(val) # Store it in dictionary but as number
        data[name.strip()] = temp_d # Store the temp_d itself in main dict
        line = fp.readline() # Now read next line
    fp.close() # Close the file
    return data # Return the data

I used simple methods, to make it easy for you. Now to access data, you have to do something like this:

x = DataExtract("your_file_path")
mul_p = x['d1']['p'] * x['d2']['p']
print(mul_p) # Tadaaa !

Feel free to comment...




回答2:


This answer is quite familiar with @JArunMani, but it's shorter a bit and sure that can run successfully.

The idea is return your data to dictionary.

lines = "d1: p,h,t,m= 74.15 18 6 0.1 ign: 0.0003\nd2: p,h,t,m= 54. 378 -0.14 0.1 ign: 0.0009".split("\n")  # lines=open("d.txt",'r').read().split("\n")
data = {}
for line in lines:
    l = line.split("ign")[0]   # remove "ign:.."
    name_dict, vals_dict = l.split(":")         #['d1',' p,h,t,m= 74.15 18 6 0.1']
    keys_str, values_str = vals_dict.split("=") #[' p,h,t,m',' 74.15 18 6 0.1']
    keys=[k for k in keys_str.strip().split(',')]       #['p','h','t','m']
    values=[float(v) for v in values_str.strip().split(' ')] #[74.15, 18, 6, 0.1]
    sub_dict = {}
    for k,v in zip(keys, values):
        sub_dict[k]=v
    data[name_dict]=sub_dict

Result:

>>>data
{'d1': {'p': 74.15, 'h': 18.0, 't': 6.0, 'm': 0.1}, 'd2': {'p': 54.0, 'h': 378.0, 't': -0.14, 'm': 0.1}}
>>>data['d1']['p']*data['d2']['p']
4004.1000000000004


来源:https://stackoverflow.com/questions/57640068/reading-a-tuple-assignment-e-g-written-as-such-d1-p-m-h-20-15-22-from

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!