Reading Formatted Text File

K

Kevin McBrearty

Hello All,

I'm trying to read a formatted text of strings and
floats. I have looked through previous posts and
couldn't deciper a good method. I'm new to python so
any suggestions would be helpful.

Regards,
Kevin

solid SIMPLEBLOCK
facet normal 0.000000e+00 0.000000e+00 -1.000000e+00
outer loop
vertex 1.000000e+00 -1.000000e+00 0.000000e+00
vertex -1.000000e+00 -1.000000e+00 0.000000e+00
vertex -1.000000e+00 1.000000e+00 0.000000e+00
endloop
endfacet



__________________________________
Do you Yahoo!?
The all-new My Yahoo! - Get yours free!
http://my.yahoo.com
 
K

Kent Johnson

Kevin said:
Hello All,

I'm trying to read a formatted text of strings and
floats. I have looked through previous posts and
couldn't deciper a good method. I'm new to python so
any suggestions would be helpful.

Here is a solution using pyparsing (http://pyparsing.sourceforge.net).
The result is a nested list structure containing the original data in a
structured form
blocktype
list of facets
normal vector
list of vertices

Kent


from pyparsing import *
import string

point = Literal( "." )
e = CaselessLiteral( "E" )
fnumber = Combine( Word( "+-"+nums, nums ) +
Optional( point + Optional( Word( nums ) ) ) +
Optional( e + Word( "+-"+nums, nums ) ) )
fnumber.setParseAction( lambda s,l,t: [ float(t[0]) ] )

triple = Group(fnumber + fnumber + fnumber)

normal = Suppress('normal') + triple
vertex = Suppress('vertex') + triple

facet = Suppress('facet') + normal + Suppress('outer loop') +
Group(OneOrMore(vertex)) + Suppress('endloop')

blockType = Word(string.uppercase)

solid = Suppress('solid') + blockType + Group(OneOrMore(facet))

data = '''
solid SIMPLEBLOCK
facet normal 0.000000e+00 0.000000e+00 -1.000000e+00
outer loop
vertex 1.000000e+00 -1.000000e+00 0.000000e+00
vertex -1.000000e+00 -1.000000e+00 0.000000e+00
vertex -1.000000e+00 1.000000e+00 0.000000e+00
endloop
endfacet
'''

print solid.parseString(data)


prints:
['SIMPLEBLOCK', [[0.0, 0.0, -1.0], [[1.0, -1.0, 0.0], [-1.0, -1.0, 0.0],
[-1.0, 1.0, 0.0]]]]
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,211
Messages
2,571,092
Members
47,693
Latest member
david4523

Latest Threads

Top