Reading Formatted Text File

Kent Johnson kent3737 at yahoo.com
Sat Nov 20 09:14:18 EST 2004


Kevin McBrearty wrote:
> 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]]]]

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



More information about the Python-list mailing list