-4

以下の形式のテキストファイルを提供しています。

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

3 に答える 3

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

チャンキング コードのクレジットは、リスト スライスの繰り返しに移動します

于 2012-06-01T23:25:24.803 に答える
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
于 2012-06-01T23:22:29.170 に答える
-1

あなたの本当の必要性については確信が持てません。しかし、あなたが示したようにファイルを出力したい場合は、テキストに区切り文字を挿入し、 re モジュールを使用して解析し、必要な順序でデータを取得できます!

于 2012-06-01T23:17:00.407 に答える