Parsing files in python

Kene Meniru Kene.Meniru at illom.org
Mon Dec 24 06:35:06 EST 2012


Chris Angelico wrote:

> On Mon, Dec 24, 2012 at 9:32 PM, Kene Meniru <Kene.Meniru at illom.org>
> wrote:
>> You are saying I can create a python module that can parse this file
>> format without using a system like python-ply? I know how to parse
>> strings using python but considering that text files that describe a
>> whole building may be quite large I thought perhaps the re module may not
>> be adequate.
> 
> Effectively, what you do is leverage the Python parser. Your script
> would look like this:
> 
> ------------possible user file content for parsing ------------
> # Boiler-plate to make this work
> from pypovray import *
> 
> # in the following the python interface program reads
> # the contents of the file "other.file" as if its content
> # were located at this point.
> import other.file
> 
> #In the following the python interface makes "snap_size" a
> #  global parameter
> snap_size = 10
> 
> 
> # In the following "buildingLevel" is a class (or function) that is
> #  called and passed the parameters in parenthesis.
> buildingLevel("FirstLevel", 3000)
> 
> # In the following "snapOffset" is a class that is
> #  called and passed the parameters in parenthesis.
> snapOffset("Closet-S1_r1", "Closet-S2_r3", (0,0,0))
> ------------end of user file content
> 
> Note the extreme similarity to your original example. Everything
> between the two snip-lines is perfectly legal Python code. (The
> semantics of a Python import aren't quite the same as a C preprocessor
> #include, so that might need a little tweaking, depending on what you
> wanted to achieve there. Possibly "from other.file import *" would do
> it.) Instead of writing a file parser, with all the complexities that
> that entails, all you need to write is a set of functions/classes that
> can be invoked.
> 
> The only part that doesn't work cleanly is the vector, since its
> syntax doesn't work in Python. You'll need to use round brackets
> instead of angle ones, as in the above example, and on output to
> Python, translate them. But that's fairly straight-forward, and by
> this method, you get *everything else* done for you - parsing, nesting
> of function calls, the entire Python standard library... the works.
> 
> ChrisA

Thanks. This makes sense and it is something I can start right away porting 
my code. Sincerely glad I voiced my thoughts. The import directive will have 
to be tackled later but that is not for at least a year or so :-)





More information about the Python-list mailing list