我想在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,但没有任何成功。 你能指点我相关的模块或策略来解决这个问题吗?
对如何处理这个问题的任何暗示将不胜感激。不只是寻找“开箱即用”解决方案。 – FLab
策略:由于您的数据结构是平坦的(这是一个文本文件),因此您需要开发自己的解析器来猜测级别,识别名称......要构建字典结构,您需要一个堆栈。 –