0

次のようなデータがあります。

Observation 1  
Type : 1  
Color: 2  

Observation 2  
Color: 2  

Resolution: 3

もともと私が行っていたのは、次のようなcsvを作成しようとすることでした:

1,2  
2,3  # Only problem here is that the data should look like this 1,2,\n ,2,3 #  

次の操作を行いました。

while linecache.getline(filename, curline):  
    for i in range(2):    
        data_manipulated = linecache.getline(filename, curline).rstrip()    
        datamanipulated2 = data_manipulated.split(":")  
        datamanipulated2.pop(0)  
        lines.append(':'.join(datamanipulated2))  

これは非常に大きなデータセットであり、上記の問題が発生しないことを確認する方法を見つけて、データを適切にコンパイルしてチェックできるようにしました。私は辞書に出くわしましたが、パフォーマンスは私にとって大きな問題であり、可能であればリストを好むでしょう (少なくとも、私の理解では、辞書は大幅に遅くなる可能性があります)。これを行うための最も迅速で最も堅牢な方法について何か提案があるかどうか疑問に思っていましたか?

4

1 に答える 1

1

次のようなものはどうですか:

input_file = open('/path/to/input.file')
results = []
for row in file:
    m = re.match('Observation (\d+)', row)
    if m:
        observation = m.group(1)
        continue
    m = re.match('Color: (\d+)', row)
    if m:
        results.append((observation, m.group(1),))
        print "{0},{1}".format(*results[-1])

コンパイル済みの正規表現を使用して高速化できます。

于 2012-05-25T05:21:34.073 に答える