2016-11-18 54 views
-2

我想在Python中导入一个类似于下面报告的文本文件。固定宽度的文本文件到Python字典

+ CATEGORY_1 first_part of long attribute <NAME_a> 
|  ...second part of long attribute 
| + CATEGORY_2: a sequence of attributes that extend over 
| |  ... possibly many <NAME_b> 
| |  ... lines 
| | + SOURCE_1 => source_code 
| + CATEGORY_2: another sequence of attributes that extend over <NAME_c> 
| |  ... possibly many lines 
| | + CATEGORY_1: yet another sequence of <NAME_d> attributes that extend over 
| | |  ...many lines 
| | | + CATEGORY_2: I really think <NAME_e> that 
| | | |  ... you got the point 
| | | |  ... now 
| | | | + SOURCE_1 => source_code 
| + SOURCE_2 => path_to_file 

凡认为我可以很容易地识别对象的名称由<为分隔...>

我的理想输出将是一个Python字典反映txt文件的层次结构,所以例如:

{NAME_a : {'category' : CATEGORY_1, 
      'depencencies' : {NAME_b : {'category' : CATEGORY_2, 
             'source_type' : SOURCE_1, 
             'source_code' : source_code} 
          NAME_c : {'category' : CATEGORY_2, 
             'dependencies' : { NAME_d : {'category' : CATEGORY_1, 
                    'dependencies' : NAME_e : {'category' : CATEGORY_2, 
                           'source_type' : SOURCE_1, 
                           'source_code' : source_code} 
                    } 
                 }   
      'source_type' : SOURCE_2, 
      'source_code : path_to_file 
      } 
} 

在认为这里的主要想法是在行开始之前计算标签数量,这将决定层次结构。 我试图看看熊猫read_fwf和numpy loadfromtxt,但没有任何成功。 你能指点我相关的模块或策略来解决这个问题吗?

+0

对如何处理这个问题的任何暗示将不胜感激。不只是寻找“开箱即用”解决方案。 – FLab

+0

策略:由于您的数据结构是平坦的(这是一个文本文件),因此您需要开发自己的解析器来猜测级别,识别名称......要构建字典结构,您需要一个堆栈。 –

回答

0

不是一个完整的答案,但你可以按照使用堆栈的方法。

每次输入类别时,都会将类别键推入堆栈。 然后你阅读这一行,检查标签的数量并存储。如果级别与先前的级别相同或更高,则从堆栈中弹出一个项目。 然后你只需要基本的正则表达式来提取项目。

一些Python /伪代码,所以你可以有一个想法

levels = [] 
items = {} 
last_level = 0 

for line in file: 
    current_level = count_tabs() 
    if current_level > last_level: 
     name = extract_name(line) 
     levels.append(name) 
     items = fill_dictionary_in_level(name, line) 
    else: 
     levels.pop() 
    last_level = current_level 

return items 
0

这里是一个战略:

对于每一行,使用正则表达式来解析线和提取数据。

这里是一个草案:

import re 

line = "| + CATEGORY_2: another sequence of attributes that extend over <NAME_c>" 

level = line.count("|") + 1 
mo = re.match(r".*\+\s+(?P<category>[^:]+):.*<(?P<name>[^>]+)>", line) 
category = mo.group("category") 
name = mo.group("name") 

print("level: {0}".format(level)) 
print("category: {0}".format(category)) 
print("name: {0}".format(name)) 

你得到:

level: 2 
category: CATEGORY_2 
name: NAME_c