2015-06-26 30 views

回答

1

np.genfromtxt可以接受迭代器閱讀:

import numpy as np 
import re 

with open('data', 'r') as f: 
    lines = (line.replace('(',' ').replace(')',' ') for line in f) 
    arr = np.genfromtxt(lines) 
print(arr) 

產生

[ 1.466 5.68 3.3 45.7  4.5  6.7  9.5 ] 

備選地,可以使用(在Python2)的str.translate或(在Python3)的bytes.translate方法,這是一個快一點:

import numpy as np 
import re 

try: 
    # Python2 
    import string 
    table = string.maketrans('()',' ') 
except AttributeError: 
    # Python3 
    table = bytes.maketrans(b'()',b' ') 

with open('data', 'rb') as f: 
    lines = (line.translate(table) for line in f) 
    arr = np.genfromtxt(lines) 
print(arr) 
+0

由於HappyLeapSecond !!這工作! –

相關問題