【发布时间】:2016-11-18 11:11:52
【问题描述】:
我正在尝试在 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
假设我可以轻松识别由 <...>
分隔的对象名称我的理想输出是反映 txt 文件层次结构的 Python 字典,例如:
{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
}
}
认为这里的主要思想是在行开始之前计算制表符的数量,这将决定层次结构。 我试图查看 pandas read_fwf 和 numpy loadfromtxt,但没有任何成功。 你能指出解决这个问题的相关模块或策略吗?
【问题讨论】:
-
任何有关如何解决该问题的提示将不胜感激。不只是寻找“开箱即用”的解决方案。
-
策略:由于你的数据结构是扁平的(它是一个文本文件),你需要开发自己的解析器来猜测水平,识别名称......要构建字典结构,你需要一个堆栈.