nsyh
nsyh

Reputation: 23

Parsing file input into variables in python

I have a text file called input.txt with the following contents:

landmark {
  x: 0.48397088050842285
  y: 0.25201746821403503
  z: -0.285147100687027
  visibility: 0.9999984502792358
}
landmark {
  x: 0.4912211298942566
  y: 0.23858927190303802
  z: -0.27364951372146606
  visibility: 0.9999926090240479
}
landmark {
  x: 0.4947235584259033
  y: 0.23917287588119507
  z: -0.27369818091392517
  visibility: 0.9999934434890747
}

How do I write a function that puts each value into a list of lists? For example: list[0] = {0.48397,0.252017,-0.28514,0.999999} list [1] = {0.491221,0.2385892,-0.27364,0.999992} and so on..

Upvotes: 0

Views: 70

Answers (2)

Surjit Samra
Surjit Samra

Reputation: 4662

Here is my approach without regx

s = """landmark {
  x: 0.48397088050842285
  y: 0.25201746821403503
  z: -0.285147100687027
  visibility: 0.9999984502792358
}
landmark {
  x: 0.4912211298942566
  y: 0.23858927190303802
  z: -0.27364951372146606
  visibility: 0.9999926090240479
}
landmark {
  x: 0.4947235584259033
  y: 0.23917287588119507
  z: -0.27369818091392517
  visibility: 0.9999934434890747
}"""
d= [i.replace('{\n','').replace('}\n','').replace('\n',',').replace(',}','') for i in s.split('landmark') if i]
t = [i.replace('x','"x"').replace('z','"z"').replace('visibility','"k"').replace('y','"y"').replace('k','visibility') for i in d]
[eval('{'+i+'}').values() for  i in t ]
#Your output: 
[dict_values([0.48397088050842285, 0.25201746821403503, -0.285147100687027, 0.9999984502792358]),
 dict_values([0.4912211298942566, 0.23858927190303802, -0.27364951372146606, 0.9999926090240479]),
 dict_values([0.4947235584259033, 0.23917287588119507, -0.27369818091392517, 0.9999934434890747])]

Upvotes: 0

Chris
Chris

Reputation: 36536

Assuming the format doesn't deviate, a very naive approach would be a whole bunch of regex substitutions to turn this into what it looks like: a list of dictionaries, and then ast.literal_eval it. A trailing comma I haven't addressed actually wraps this up a single element tuple, hence the [0].

import ast
import re

ast.literal_eval(
  re.sub(r'(\d)\s', r'\1,', 
  re.sub(r'\}\s*landmark\s*{', '},{', 
  re.sub(r'$', ',', 
  re.sub(r'\}\s*\Z', '}]', 
  re.sub(r'\Alandmark\s*\{', '[{', 
  re.sub(r'([a-zA-Z]+):', r'"\1":', s))))))
)[0]

Upvotes: 1

Related Questions