使np.loadtxt与多个可能的分隔符一起使用 [英] Making np.loadtxt work with multiple possible delimiters
问题描述
我有一个程序可以读取数据文件,用户可以选择要使用的列.我希望它在输入文件中更通用;有时,列看起来可能像这样:
I have a program that reads in data files and the user selects which column they want to use. I want it to be more universal with input files; sometimes, columns can look like this:
10:34:24.58 8.284 6.121
有时它们看起来可能像这样:
And sometimes they can look like this:
10 34 24.58 8.284 6.121
我希望程序在两种情况下都将其识别为5列,而不是第一列为5列,第二列为3列.基本上,我希望它能够将white space
识别为定界符,并且将:
识别为定界符.
I want the program to recognize this as 5 columns in BOTH cases, instead of 5 columns for the first and 3 for the second. Basically, I want it to recognize white space
as a delimiter and :
as a delimiter as well.
有没有简单的方法可以做到这一点?我知道numpy需要一个定界符命令,但据我所知它只能使用一个.
Is there a simple way to do this? I know numpy takes a delimiter command, but as far as I'm aware it can only use one.
推荐答案
感谢上面的回答,但是我相信我已经找到了一种解决方法,该方法可以实现简单的两行解决方案,而无需修改程序的其余部分.
Thanks to the answer above, but I believe I've found a workaround that allows for a simple two-line solution, without modifying the rest of my program.
初始的loadtxt行如下所示:
The initial loadtxt line looked like this:
import numpy as np
...
data = np.loadtxt(filename,skiprows=header,dtype=str)
通过使用StringIO,我们可以简单地读取文件并将':'
的每个实例替换为" "
,而无需修改任何其他代码.
By utilizing StringIO, we can simply read the file and replace every instance of ':'
with " "
, without having to modify any of the other code.
import numpy as np
import StringIO
...
s = open(filename).read().replace(':',' ')
data = np.loadtxt(StringIO.StringIO(s),skiprows=header,dtype=str)
我希望这对其他人有帮助!
I hope this helps someone else!
这篇关于使np.loadtxt与多个可能的分隔符一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!