2014-10-01 99 views
-3

在python中我試圖解析.txt文件,它具有下面描述的構造。我需要獲取部分塊下的所有行,然後執行其他行的其他操作。請注意,這不是配置文件,所以我不能使用解析conf文件的標準方式。解析.txt文件,其中包含部分

LINE 1 
LINE 2 

[Section1] 
LINE 1 
LINE 2 
LINE 3 

[Section2] 
LINE 1 
LINE 2 
+0

每個部分都標有'[section#]'? – phyrox 2014-10-01 11:32:09

+1

這似乎有點像「你能爲我做我的任務嗎」。請嘗試自己解決它,如果它不起作用,請粘貼您的代碼並告訴它到底是什麼問題。 如果問題是關於找到一個用這種格式解析文件的庫,請更清楚地說出來。 – Zds 2014-10-01 12:07:21

回答

2

首先,(我的解決方案),您需要拆分所有內容並過濾空行:

text = filter(None, map(lambda x: x.strip(), text.split("\n")))

假設您的默認部分稱爲default

current_section = "default" result_parsing = {"default" : []} for line in text: if line[0] == "[" and line[-1] == "]": current_section = line[1:-1] result_parsing[current_section] = [] else: result_parsing[current_section].append(line)

+0

是的,我認爲這個代碼應該工作。 – 2014-10-01 11:43:09