Python text file searching for values and compiling results found -
i have large text file of lots of experimental results search through specific pieces of data, need compile. text file has results many different experiments, , need keep data each experiment together.
e.g. (not actual data)
object 1 colour of object blue. size of object 0.5 m^3 mass of object 0.8 g object 2 colour of object pink. size of object 0.3m^3 etc.
i know values want be, can search text specific phrase know present on line data on.
one way thought of doing search through file each specific line (i'm looking 2 different variables), , add value needed list. create dictionary each object, assuming @ same number in each list data same object.
e.g.
variable_one = [] variable_two = [] def get_data(file): open("filename.txt", "r") file: 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, search through file , create list, each entry being section of data different object, searching 2 variables each object within different items in list - again storing values each object in dictionary.
what want know if there more efficient/better method doing ideas had?
here alternative uses 1 list , uses less "append" , less "in" , should more effective.
variables = [] open('filename.txt') input: colour = mass = '' line in input: fields = line.split() if len(fields)>6: value = fields[6] if 'the colour' in line: colour = value elif 'the mass' in line: mass = value elif line.startswith('object'): variables.append((colour, mass)) colour = mass = '' # may not needed. del(variables[0])
Comments
Post a Comment