【问题标题】:good python strategy for parsing grammar-based file format解析基于语法的文件格式的好python策略
【发布时间】:2013-01-18 02:23:18
【问题描述】:

我已经为 PLY 和 OBJ 等 3D 文件格式编写了很多简单的导入器,它们似乎具有非常基于状态的每行结构,使得解析变得非常容易。我的朋友希望我使用 python 为来自 mirai 的文件类型实现一个简单的导入器,我注意到可以有很多分层表示的数据,这与我之前使用的更简单的逐行格式不同。

我想知道我是否应该尝试使用一些 python 库、一些复杂的正则表达式为此创建一个完整的语法,或者我应该使用字符串替换来破解一些解决方案。任何人都可以为解析这种类型的文件提供任何好的建议吗?这个特定示例是一个导出的多维数据集。

 filetype gx;
 GrammarVersion 2.1.0.0;
 TemplateVersion 2.1.0.0;
 HostName "ZOO-HP";
 UserName "Phil";
 TimeStamp "Mon 20-Aug-12, 9:48 pm";
 OSName "Windows NT 6.01.7601";
 ApplicationName "Mirai";
 ApplicationVersion "1.1.0.1 5629";
 include "gbf-2-1-0-0.tpl";
 include "cube_mirai.gmf";


 body Polyhedron-31 (

   vertices[] < (
coord -0.500000 -0.500000 0.500000 ;
 )
 (
coord -0.500000 0.500000 0.500000 ;
 )
 (
coord 0.500000 0.500000 0.500000 ;
 )
 (
coord 0.500000 -0.500000 0.500000 ;
 )
 (
coord 0.500000 -0.500000 -0.500000 ;
 )
 (
coord 0.500000 0.500000 -0.500000 ;
 )
 (
coord -0.500000 0.500000 -0.500000 ;
 )
 (
coord -0.500000 -0.500000 -0.500000 ;
 )
>
   faces[] < (
normal 0.000000 0.000000 1.00000 ;
      vertex-indices[] <0;1;2;3;>
      vertex-normal-indices[] <0;1;2;3;> )
 (
normal 0.000000 0.000000 -1.00000 ;
      vertex-indices[] <4;5;6;7;>
      vertex-normal-indices[] <4;5;6;7;> )
 (
normal 0.000000 1.00000 0.000000 ;
      vertex-indices[] <1;6;5;2;>
      vertex-normal-indices[] <1;6;5;2;> )
 (
normal 0.000000 -1.00000 0.000000 ;
      vertex-indices[] <7;0;3;4;>
      vertex-normal-indices[] <7;0;3;4;> )
 (
normal 1.00000 0.000000 0.000000 ;
      vertex-indices[] <3;2;5;4;>
      vertex-normal-indices[] <3;2;5;4;> )
 (
normal -1.00000 0.000000 0.000000 ;
      vertex-indices[] <7;6;1;0;>
      vertex-normal-indices[] <7;6;1;0;> )
>
   normals[] <-0.577350 -0.577350 0.577350 ;
-0.577350 0.577350 0.577350 ;
0.577350 0.577350 0.577350 ;
0.577350 -0.577350 0.577350 ;
0.577350 -0.577350 -0.577350 ;
0.577350 0.577350 -0.577350 ;
-0.577350 0.577350 -0.577350 ;
-0.577350 -0.577350 -0.577350 ;
>
 )

【问题讨论】:

  • 目前尚不清楚破解的“字符串替换”与此处的相关性,它与使用正则表达式等解析文本的初始问题提出了不同的问题。

标签: python parsing format grammar


【解决方案1】:

要解析这么大的结构,我会避免手工制作复杂的正则表达式;它们的维护/调试成本太高。

我会转而看一下PyParsing,它有相当多的examplesPLY

其中任何一个都可以让您以更结构化的方式解析文件,这应该更易于维护。它们还将更容易扩展到简单的立方体示例之外,以涵盖 mirai 文件格式的全部范围。

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 2018-10-05
    • 2011-06-17
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 1970-01-01
    相关资源
    最近更新 更多