2015-12-09 75 views
1

我正在嘗試使用numpy.genfromtxt()方法從txt文件中提取值。我的txt文件看起來是這樣的:不同列大小的NumPy genfromtxt

'! dt   tot   nsave  readext\n', 
' 0.002  200   500  F\n', 
'!----------------------------------------------------------------------\n', 
'! xdomain  ydomain \n', 
' 7.5   7.5\n', 
'!----------------------------------------------------------------------\n', 
'! maxnewts maxiters atol\n', 
' 40  100  0.001\n', 
'!----------------------------------------------------------------------\n', 
'! p  \n', 
' 600 \n', 

但使用numpy.genfromtxt("file.txt", comments='!')給我:

Line #4 (got 2 columns instead of 4) 
Line #7 (got 3 columns instead of 4) 
Line #10 (got 1 columns instead of 4) 

我怎樣才能讓numpy.genfromtxt靈活的對列的大小?

回答

1

看起來文本文件的分析格式不正確。我會建議使用csv得到你需要出來的文件是什麼,然後用numpy

import csv 
clean_vars = [] 
with open('foo.txt', 'r') as csvfile: 
    reader = csv.reader(csvfile, delimiter=' ', quotechar=",") 
    for row in reader: 
     # clean up your file here and append it to the list 
     clean_vars.append([char for char in row if char]) 

# do your processing with numpy with your clean vars 

做你的處理在上述情況下,我低效清洗瓦爾作爲一個例子。 csv的文檔可以在https://docs.python.org/2/library/csv.html