我正试图使用numpy.genfromtxt()方法从txt文件中提取值。我的txt文件如下所示:
'! dt tot nsave readextn',
' 0.002 200 500 Fn',
'!----------------------------------------------------------------------n',
'! xdomain ydomain n',
' 7.5 7.5n',
'!----------------------------------------------------------------------n',
'! maxnewts maxiters atoln',
' 40 100 0.001n',
'!----------------------------------------------------------------------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
在列大小方面具有灵活性?
文本文件的格式似乎不适合分析。我建议使用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
在上面的例子中,我正在低效地清洁vars。csv的文档可在https://docs.python.org/2/library/csv.html