Wednesday, 7 August 2013

Python text file searching for values and compiling results found

Python text file searching for values and compiling results found

I have a large text file of lots of experimental results to search through
for specific pieces of data, which I need to compile. The text file has
results from many different experiments, and I need to keep the data from
each experiment together.
e.g. (Not the actual data)
Object 1
The colour of the object is blue.
The size of the object is 0.5 m^3
The mass of the object is 0.8 g
Object 2
The colour of the object is pink.
The size of the object is 0.3m^3
etc.
I know where the values I want will be, as I can search the text for a
specific phrase that I know will be present on the line the data is on.
One way I thought of doing it would be to search through the file for each
specific line (I'm looking for two different variables), and add the value
needed to a list. From this I would then create a dictionary for each
object, assuming that at the same number in each list will be data from
the same object.
e.g.
variable_one = []
variable_two = []
def get_data(file):
with open("filename.txt", "r") as file:
for line in file:
if "The colour" in line:
variable_one.append(line.split()[6])
if "The mass" in line:
variable_two.append(line.split()[6])
file.close()
or, to search through the file and create a list, with each entry being
the section of data from a different object, then searching for the two
variables for each object from within the different items in the list -
again eventually storing the values from each object in a dictionary.
What I want to know is if there is a more efficient/better way of doing
this than the ideas I had?
Sorry about the lengthy explanation

No comments:

Post a Comment