【发布时间】:2015-01-22 15:18:42
【问题描述】:
我刚刚学习 Python,还不熟悉所有术语。我有以下我想在 Python 中执行的 Matlab 代码。
- 将文本文件读入结构(记录/列表?)
- 在字段(字符串数组)中搜索特定值。
- 在另一个字段中使用该索引
sampleData.txt
name descript sr type scale offset
a Param_a 10 int8 1 0
b Param_b 20 unit 2 -10
c Param_c 30 int8 3 -20
d Param_d 40 int8 4 -30
e Param_e 50 uint 5 -40
Matlab 代码:
>> [info.name info.descrip info.sr info.type info.scale info.offset] = textread('sampleData.txt','%s\t%s\t%f\t%s\t%f\t%f','headerlines',1);
info =
name: {5x1 cell}
descrip: {5x1 cell}
sr: [5x1 double]
type: {5x1 cell}
scale: [5x1 double]
offset: [5x1 double]
>> nameIdx = strcmp(info.name,'b') ;
>> matched_sr = info.sr(nameIdx)
matched_sr =
20
在 python 中,我可以使用 numpy 读取文本文件:
info= recfromcsv('sampleData.txt', delimiter='\t')
Out:
rec.array([(b'a', b'Param_a', 10, b'int8', 1, 0),
(b'b', b'Param_b', 20, b'unit', 2, -10),
(b'c', b'Param_c', 30, b'int8', 3, -20),
(b'd', b'Param_d', 40, b'int8', 4, -30),
(b'e', b'Param_e', 50, b'uint', 5, -40)],
dtype=[('name', 'S1'), ('descript', 'S7'), ('sr', '<i4'), ('type', 'S4'), ('scale', '<i4'), ('offset', '<i4')])
我可以执行以下操作来获取逻辑数组:
In [77]: info.sr == 20
Out[77]: array([False, True, False, False, False], dtype=bool)
但是对于 info.name 来说同样的事情不起作用。
In [78]: info.name == 'b'
Out[78]: False
那么,我如何像在 matlab 中使用 strcmp 那样通过“名称”找到参数?此外,更一般地说,Python/numpy 中是否有更好的方法将文本文件作为数组(记录或列表?)读取?抱歉,我还是个新手,有任何不正确的 Python 行话。
谢谢,
【问题讨论】: