繁体   English   中英

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

在上述情况下,我以效率低下的var清理为例。 可以在https://docs.python.org/2/library/csv.html上找到csv的文档

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM