Read file information. txt using Python

0

Good evening!

I have a .txt file that stores a data structure as follows:

índice: p1[x1, y1], p2[x2, y2], p3[x3, y3], p4[x4,y4]

An example of lines from my file is:

1: p1 = [62.61, 79.47], p2 = [64.17, 75.43], p3 = [58.85, 72.5], p4 = [57.45, 76.6]
2: p1 = [64.17, 75.43], p2 = [68.63, 63.22], p3 = [63.59, 60.71], p4 = [58.85, 72.5]

So, I'd like to know how I can just extract the important data from my file and store it in variables using Python language. In this case, the data of interest are the numeric values, which correspond to Cartesian coordinates.

Any help is welcome! :)

    
asked by anonymous 13.11.2018 / 22:24

1 answer

2

You can use regular expressions to parse these lines.

import re
with open('seu_arquivo.txt') as f:
    for linha in f:
        indice, restante = linha.split(':', 1)
        registro = {k: (float(v1), float(v2)) for k, v1, v2 in 
            re.findall(r'(\w+) = \[([\d.]+), ([\d.]+)\]', restante)}
        registro['indice'] = indice
        print(registro)
        # resultado.append(registro) # armazena em lista se precisar?
        # pode acessar as variaveis usando registro['p2'] etc

Running with your example, you left:

{'p1': (62.61, 79.47), 'p2': (64.17, 75.43), 
 'p3': (58.85, 72.5), 'p4': (57.45, 76.6), 'indice': '1'}

{'p1': (64.17, 75.43), 'p2': (68.63, 63.22), 
 'p3': (63.59, 60.71), 'p4': (58.85, 72.5), 'indice': '2'}
    
14.11.2018 / 01:22