0

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..

2
  • 3
    What format is this in? Your best bet would be to find a library that parses that format, rather than you writing the parsing yourself. Commented Jan 1, 2023 at 7:37
  • 2
    Agreed, your best bet it to get the exact format of your source. But if it always comes like this you could write a small parser. Commented Jan 1, 2023 at 7:42

2 Answers 2

1

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]
Sign up to request clarification or add additional context in comments.

Comments

0

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])]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.