0

I have the following string which i would like to extract the variables and their values

text = "family:'DefaultCroSec' name:'' I-Profile:  height:60[cm] Upper-width:35[cm] Lower-width:190[cm] Upper-thick:2[cm] Lower-thick:1.4[cm] Fillet-radius:0[cm] Web-thick:1[cm] zs:15.28[cm] material:'S355' applies to elements:'girders'"

i.e

height = 60
Upper-width = 35

etc etc

What is the best way to do this?

2
  • 1
    Since this string does not look like any valid python dictionary or JSON code, maybe use splitting to get the names and the values of the "variables" and store them in a dictionary. Commented Apr 17, 2021 at 6:39
  • 1
    There doesn't seem to be any consistent pattern. Sometimes the value is surrounded by quotes, sometimes it isn't. Commented Apr 17, 2021 at 6:44

1 Answer 1

3

Using Regex.

import re
text = "family:'DefaultCroSec' name:'' I-Profile:  height:60[cm] Upper-width:35[cm] Lower-width:190[cm] Upper-thick:2[cm] Lower-thick:1.4[cm] Fillet-radius:0[cm] Web-thick:1[cm] zs:15.28[cm] material:'S355' applies to elements:'girders'"

print(dict(re.findall(r"([\w\-]+):(\d+\.?\d*)", text)))

Output:

{'Fillet-radius': '0',
 'Lower-thick': '1.4',
 'Lower-width': '190',
 'Upper-thick': '2',
 'Upper-width': '35',
 'Web-thick': '1',
 'height': '60',
 'zs': '15.28'}
Sign up to request clarification or add additional context in comments.

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.