Chip Burwell Chip Burwell - 1 month ago 9
Python Question

Parse text position vector to floats

I have a .txt file that contains lines in this format:

{"Position":[81.2305,4.05698,9.14912]}


Because I have lots of other lines that start with an open bracket and a name enclosed in quotes followed by a semi-colon, I have split the line into two like this:

[ '{"Position":', '[81.2305,4.05698,9.14912]}' ]


I would like to parse the second string into a list of 3 floats. What is the best way to do this?

Answer

Your data looks like JSON, so you can use the built-in JSON module:

import json

pos = [] # list of (x,y,z)

with open('t.txt') as infile:
    for line in infile:
        # skip blank lines (add other cases as needed)
        if not line.strip():
            continue

        item = json.loads(line)
        if "Position" in item:
            pos.append(item["Position"])

print(pos)
Comments