2016-04-12 20 views
0

分離TXT數據我有一個txt文件的一些數據如下:閱讀用空行幾個numpy的陣列

# Contour 0, label:  37 
41.6 7.5 
41.5 7.4 
41.5 7.3 
41.4 7.2 

# Contour 1, label: 
48.3 2.9 
48.4 3.0 
48.6 3.1 

# Contour 2, label: 
61.4 2.9 
61.3 3.0 
.... 

所以每塊從評論和一個空行結束。 我想讀出這些數據並將其納入其中包括numpy的陣列的列表,所以像

# list as i want it: 
[array([[41.6, 7.5], [41.5, 7.4], [1.5, 7.3], [41.4, 7.2]]), 
array([[48.3, 2.9], [48.4, 3.0], [48.6, 3.1]]), 
array([[61.4, 2.9], [61.3, 3.0]]), ...] 

是否有一個有效的方式來做到這一點與numpy的? genfromtxtloadtxt似乎沒有必要的選項!?

+0

'loadtxt'和'genfromtxt'並不是特別有效。他們只是逐行閱讀輸入,做一個「分裂」,並收集列表中的值。轉換是結束。對於簡單的浮動,你自己的讀者將會一樣好。 – hpaulj

+0

早先有關於通過塊讀取csv的SO問題。讀者接受來自任何來源的線路。寫你自己的過濾器或發電機。 – hpaulj

回答

1

你可以使用Python的groupby功能組中的3項一起如下:

from itertools import groupby 
import numpy as np 

array_list = [] 

with open('data.txt') as f_data:  
    for k, g in groupby(f_data, lambda x: x.startswith('#')): 
     if not k: 
      array_list.append(np.array([[float(x) for x in d.split()] for d in g if len(d.strip())])) 

for entry in array_list: 
    print entry 
    print 

這將顯示array_list如下:

[[ 41.6 7.5] 
[ 41.5 7.4] 
[ 41.5 7.3] 
[ 41.4 7.2]] 

[[ 48.3 2.9] 
[ 48.4 3. ] 
[ 48.6 3.1]] 

[[ 61.4 2.9] 
[ 61.3 3. ]] 
+0

我需要一段時間才能理解它爲什麼以及如何工作。哇謝謝! – Geri

0

是否這樣?

import numpy as np 

text = \ 
''' 
# Contour 0, label:  37 
41.6 7.5 
41.5 7.4 
41.5 7.3 
41.4 7.2 

# Contour 1, label: 
48.3 2.9 
48.4 3.0 
48.6 3.1 

# Contour 2, label: 
61.4 2.9 
61.3 3.0 
''' 
for line in text.split('\n'): 
    if line != '' and not line.startswith('#'): 
     data = line.strip().split() 
     array = np.array([float(d) for d in data]) 
     print(array)