我正在尝试使用numpy.genfromtxt()方法从txt文件中提取值。我的txt文件如下所示:
'! 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
对列大小保持灵活性?
答案 0 :(得分: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
在上面的例子中,我作为一个例子无效地清理变量。可以在https://docs.python.org/2/library/csv.html
找到csv的文档