需要解析文件并从中创建数据结构

问题描述 投票:0回答:1

我们想要解析一个文件并创建一个稍后使用的某种数据结构(在Python中)。 文件内容如下所示:

plan HELLO
   feature A 
       measure X :
          src = "Type ,N ame"
       endmeasure //X

       measure Y :
        src = "Type ,N ame"
       endmeasure //Y

       feature Aa
           measure AaX :
              src = "Type ,N ame"
           endmeasure //AaX

           measure AaY :
              src = "Type ,N ame"
           endmeasure //AaY
           
           feature Aab
              .....
           endfeature // Aab
         
       endfeature //Aa
 
   endfeature // A
   
   feature B
     ......
   endfeature //B
endplan

plan HOLA
endplan //HOLA

因此有一个文件包含一个或多个计划,然后每个计划包含一个或多个功能, 此外,每个特征都包含一个包含信息(src、类型、名称)的度量,并且特征可以进一步包含更多特征。

我们需要解析文件并创建一个数据结构

                     plan (HELLO) 
            ------------------------------
             ↓                          ↓ 
          Feature A                  Feature B
  ----------------------------          ↓
   ↓           ↓             ↓           ........
Measure X    Measure Y    Feature Aa
                         ------------------------------
                            ↓           ↓             ↓ 
                       Measure AaX   Measure AaY   Feature Aab
                                                        ↓
                                                        .......

我试图逐行解析文件并创建一个列表列表,其中包含 计划 -> 功能 -> 测量、功能

python list data-structures readlines fileparse
1个回答
0
投票

为了快速而肮脏的解析,您可以进行一些正则表达式替换,例如

text = re.sub(
    r'(?mx)^ \s* (plan|feature|measure) \s+ (\w+) .*',
    '<\\1 name="\\2">',
    text)
text = re.sub(
    r'(?mx)^ \s* end (\w+) .*',
    '</\\1>',
    text)
text = re.sub(
    r'(?mx)^ \s* (\w+) \s*=\s* (.*)',
    '<\\1>\\2</\\1>',
    text)

这会将其转换为 XML,您可以使用内置工具进行解析,例如E树。

© www.soinside.com 2019 - 2024. All rights reserved.