不同列大小的 NumPy genfromtxt
NumPy genfromtxt for different column sizes
我正在尝试使用 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
灵活调整列大小?
文本文件的格式似乎不正确,无法进行分析。我建议使用 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
找到
我正在尝试使用 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
灵活调整列大小?
文本文件的格式似乎不正确,无法进行分析。我建议使用 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
找到