2016-11-17 19 views
0

我有一個從外部應用程序導出爲CSV文件等讀CSV而分組行

15/07/2008 2:48:53 PM 

Measurement device:; dvp3445 
Field detector:; Diode 
Reference detector:; Undefined 
Scan mode:; Continuous 

Points [mm]: 
X; Y; Depth; Normalized field; Current field; Ratio 
0.0; -109.0; 20.0; 1.3; 0; 0.0 
0.0; -108.7; 20.0; 1.3; 0; 0.0 
0.0; -108.4; 20.0; 1.3; 0; 0.0 
0.0; -108.0; 20.0; 1.3; 0; 0.0 
0.0; -107.7; 20.0; 1.3; 0; 0.0 


15/07/2008 5:28:50 PM 

Measurement device:; dvp3445 
Field detector:; Diode 
Reference detector:; Undefined 
Scan mode:; Continuous 

Points [mm]: 
X; Y; Depth; Normalized field; Current field; Ratio 
0.0; -108.7; 40.0; 1.3; 0; 0.0 
0.0; -108.4; 40.0; 1.4; 0; 0.0 
0.0; -108.1; 40.0; 1.4; 0; 0.0 
0.0; -107.8; 40.0; 1.4; 0; 0.0 
0.0; -107.5; 40.0; 1.5; 0; 0.0 
0.0; -107.2; 40.0; 1.6; 0; 0.0 
0.0; -106.9; 40.0; 1.6; 0; 0.0 


15/07/2008 5:28:50 PM 

Measurement device:; dvp3445 
Field detector:; Diode 
Reference detector:; Undefined 
Scan mode:; Continuous 

Points [mm]: 
X; Y; Depth; Normalized field; Current field; Ratio 
0.0; -106.6; 40.0; 1.7; 0; 0.0 
0.0; -106.3; 40.0; 1.8; 0; 0.0 
0.0; -106.0; 40.0; 1.8; 0; 0.0 
0.0; -105.7; 40.0; 1.9; 0; 0.0 
0.0; -105.4; 40.0; 2.0; 0; 0.0 
0.0; -105.1; 40.0; 2.1; 0; 0.0 
0.0; -104.8; 40.0; 2.2; 0; 0.0 
0.0; -104.5; 40.0; 2.3; 0; 0.0 

1.4 Python的CSV讀者的任何處理這種情況因爲我找的輸出3列,每列對應於點標題X; Ÿ;深度;標準化場;當前字段;比。

我試圖使用正則表達式解析來實現這一點,但它不起作用。有人可以分享一些想法嗎?

GT

+0

試試我的解決方案 – eyllanesc

回答

0

由於csv模塊中的讀取器類被初始化與字符串iterables,它將足以塊出線的適當塊:

import csv 

f = open('data.txt', 'r') 
lines = [l for l in f if len(l.split(';')) == 6] # filter relevant lines 
bounds = [i for i, line in enumerate(lines) if line[0] == 'X'] + [len(lines)] 
bounds = zip(bounds, bounds[1:]) # [(0, 6), (6, 14), (14, 23)] 
line_blocks = [lines[start: end] for start, end in bounds] 

csv_readers = [csv.DictReader(block, delimiter=';', skipinitialspace=True) for block in line_blocks] 

現在,每個閱讀器是一個可迭代過dict將標題作爲關鍵字的實例。

r = csv_readers[0] 
for record in r: 
    print record 

{'Ratio': '0.0', 'Depth': '20.0', 'Normalized field': '1.3', 'Current field': '0', 'Y': '-109.0', 'X': '0.0'} 
{'Ratio': '0.0', 'Depth': '20.0', 'Normalized field': '1.3', 'Current field': '0', 'Y': '-108.7', 'X': '0.0'} 
{'Ratio': '0.0', 'Depth': '20.0', 'Normalized field': '1.3', 'Current field': '0', 'Y': '-108.4', 'X': '0.0'} 
{'Ratio': '0.0', 'Depth': '20.0', 'Normalized field': '1.3', 'Current field': '0', 'Y': '-108.0', 'X': '0.0'} 
{'Ratio': '0.0', 'Depth': '20.0', 'Normalized field': '1.3', 'Current field': '0', 'Y': '-107.7', 'X': '0.0'} 
+0

謝謝@schwobaseggl:但我的預期結果是0.0; -106.6; 40.0; '1.7; 0; 0.0 0.0; -106.3; 40.0; 1.8; 0; 0.0 0.0; -106.0; 40.0; 1.8; 0; 0.0 0.0; -105.7; 40.0; 1.9; 0; 0.0 0.0; -105.4; 40.0; 2.0; 0; 0.0 0.0; -105.1; 40.0; 2.1; 0; 0.0 0.0; -104.8; 40.0; 2.2; 0; 0.0 0.0; -104.5; 40.0; 2.3; 0; 0.0' – user1301295