Python Forum
help parsing file - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: help parsing file (/thread-21874.html)



help parsing file - aslezak - Oct-18-2019

I'm looking for general guidance/suggestions on how to extract grid data points from a text file. Lines beginning with "GRID*" have node numbers and x y z coordinate information. I would like to extract that information. Each "GRID" line is segmented into '6' columns. The first and last column are eight characters wide, columns 2,3,4, and 5 are 16 characters wide. An example coordinate would be '-3.69374569427+0'. I would also like to know how to convert that format into a real number. I studied the "strings" documentation but haven't found an answer on my own yet. Any help/suggestions/guidance appreciated.

Thanks!,
Andrew

sample file contents:

Output:
GRID* 1 0-3.69374569427+09.077207667771+0 * 5.000014684254-1 0 GRID* 2 0-3.69374569427+0-9.07720766777+0 * 4.999985315745-1 0 GRID* 3 08.978071514315+03.928573996764+0 * 4.999963281080-1 0 GRID* 4 08.978071514315+0-3.92857399676+0 * 5.000036718919-1 0
etc..

PS.
I tried to show the "column widths" in the sample file contents but the forum post removes the white space. The coordinate information begins in column 4 and continues on the next line. For anyone curious, this is from a NASTRAN input file


RE: help parsing file - buran - Oct-18-2019

please, use output tags to show the correct format of the file
See BBcode help for more info.


RE: help parsing file - aslezak - Oct-22-2019

This is what I have so far. I'm not sure how robust it is

import csv
import tkinter as tk
from tkinter import filedialog
from math import *

root = tk.Tk()
root.withdraw()

#opened file must be NASTRAN input file. Check .nas extension
file_path = filedialog.askopenfilename()

nas = open(file_path ,mode = 'r', encoding = 'utf-8')

n=[]
x=[]
y=[]
z=[]
nextline = 0
for line in nas:
    if line[:4] == "GRID":
        nextline = 1
        n.append(line[8:8 + 16])
        x.append(line[8 + 2*16:8+3*16])
        y.append(line[8 + 3*16:8+4*16])
        continue    
    if nextline == 1:
        z.append(line[8:8+16])
        nextline = 0

def scientific(coord):
    ind = 0
    for i in coord:
        if i.find('+') > -1:
            coord[ind] = i.replace('+', 'E+')
        elif i.find('-') > -1:
            if i.find('-') == 0:
                s = i.lstrip('-')
                i = '-' + s.replace('-', 'E-')
            else:
                i = i.replace('-', 'E-')
            coord[ind] = i
        ind = ind + 1    

scientific(x)
scientific(y)
scientific(z)
        
with open('gridout.csv', 'w', newline='') as csvFile:
    writer = csv.writer(csvFile)
    index = 0
    for i in n:
        writer.writerow([n[index], x[index], y[index], z[index]])
        index = index + 1

nas.close()