2012-06-01 78 views
-4

我給下面的格式的文本文件:的Python更改文本文件的格式爲新的格式

3  Bham Hoover - Vestiva 
123 234 1 456 876 1 876 745 1 
0 
4  Bham Vestiva - Greensprings 
235 876 1 647 987 1 098 765 1 234 546 1 
0 

這正好爲幾個行,但我想這種格式轉換爲如下:

Event 
Disconnect branch from bus 123 to 234 circuit 1 
Disconnect branch from bus 456 to 876 circuit 1 
Disconnect branch from bus 876 to 745 circuit 1 
end 
Event 
Disconnect branch from bus 235 to 876 circuit 1 
Disconnect branch from bus 647 to 987 circuit 1 
Disconnect branch from bus 098 to 765 circuit 1 
Disconnect branch from bus 234 to 546 circuit 1 
end 
+4

而你的問題是什麼? –

+2

請用一個問題來更新你的問題。 – jgritty

+0

Fyi,StackOverflow不是'plz給我發送代碼'的網站。下一次向我們展示您嘗試的是什麼,而不是讓我們爲您編寫代碼。 – ThiefMaster

回答

1
from itertools import islice 
with open('file.txt', 'r') as f: 
    # iterate over every 3rd line, starting with the 2nd 
    for line in islice(f, 1, None, 3): 
     parts = line.split() 
     print 'Event' 
     # iterate over 3-element chunks 
     for x in zip(*(iter(parts),) * 3): 
      print 'Disconnect branch from bus %s to %s circuit %s' % x 
     print 'end' 

輸出:

Event 
Disconnect branch from bus 123 to 234 circuit 1 
Disconnect branch from bus 456 to 876 circuit 1 
Disconnect branch from bus 876 to 745 circuit 1 
end 
Event 
Disconnect branch from bus 235 to 876 circuit 1 
Disconnect branch from bus 647 to 987 circuit 1 
Disconnect branch from bus 098 to 765 circuit 1 
Disconnect branch from bus 234 to 546 circuit 1 
end 

積分的分塊碼去Iteration over list slices

+0

在這裏大量使用評論。 – Droogans

-1

我不確定你的真正需要。但是如果你想輸出你的文件,就像你顯示的那樣,你可以在你的文本中插入一個分隔符,然後使用re模塊解析然後按照你需要的順序獲取數據!

+0

由於數據行包含任意數量的數據三元組,因此正則表達式對於此格式並不是一個好選擇。有更好的方法來解析這個 - 看到休的答案或我的。 – ThiefMaster

+0

絕對可以看到ThiefMaster的回答,特別是使用一個文件對象作爲生成器,並用'islice'(我每天在這裏學到新的東西)滑雪線。 – Droogans

0
with open("data.txt") as inf: 
    for head,data,tail in zip(inf,inf,inf): 
     print("Event") 
     items = iter(data.split()) 
     for bus1,bus2,cct in zip(items,items,items): 
      print("Disconnect branch from bus {} to {} circuit {}".format(bus1,bus2,cct)) 
     print("end") 

結果

Event 
Disconnect branch from bus 123 to 234 circuit 1 
Disconnect branch from bus 456 to 876 circuit 1 
Disconnect branch from bus 876 to 745 circuit 1 
end 
Event 
Disconnect branch from bus 235 to 876 circuit 1 
Disconnect branch from bus 647 to 987 circuit 1 
Disconnect branch from bus 098 to 765 circuit 1 
Disconnect branch from bus 234 to 546 circuit 1 
end