我想在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
策略:由於您的數據結構是平坦的(這是一個文本文件),因此您需要開發自己的解析器來猜測級別,識別名稱......要構建字典結構,您需要一個堆棧。 –