Read file information. txt using Python

Asked

Viewed 559 times

2

Good night!

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

Thus, I would like to know how to extract only the important data from my file and store it in variables using Python language. In this case, the data of interest are the numerical values, which correspond to the Cartesian coordinates.

Any help is welcome! :)

  • 2

    Are 4 points per line ? Are you the one who controls the file format ? If yes then you are complicating something that you can do very simply with a csv for example

1 answer

4

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, came out:

{'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'}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.