Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how do I find and get text from a text file in python?

I have a text file with lines like this one:

Cubo: 100% (left_x: 744 top_y: 395 width: 167 height: 181)

I would like to assign the appropiate int for each one of the variables, something like: left_x = 744, top_y = 395, width = 167, height = 181 but without having to do it manually.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You should probably use a dictionary, not variables, but you can use regex to parse it. E.g.

import re

s = 'Cubo: 100% (left_x:  744   top_y:  395   width:  167   height:  181)'
fields = s[s.index('(')+1:-1]
data = {x[0]:int(x[1]) for x in re.findall(r'([a-z_]+):\s+(\d+)', fields)}
print(data['left_x']) #  744
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading