【问题标题】:Matlab to Python conversion: Read a text file into numpy records and search array for a stringMatlab 到 Python 的转换:将文本文件读入 numpy 记录并在数组中搜索字符串
【发布时间】:2015-01-22 15:18:42
【问题描述】:

我刚刚学习 Python,还不熟悉所有术语。我有以下我想在 Python 中执行的 Matlab 代码。

  1. 将文本文件读入结构(记录/列表?)
  2. 在字段(字符串数组)中搜索特定值。
  3. 在另一个字段中使用该索引

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 行话。

谢谢,

【问题讨论】:

    标签: python matlab numpy


    【解决方案1】:

    看起来您正在使用Python3,它默认使用 unicode 字符串。但是数据文件是 ASCII,所以字符串作为字节数组加载。所以所有字符串都显示为b

    所以要进行比较,您需要将字节字符串与字节字符串进行比较。

    试试:

    info.name == b'b'
    

    例如

    In [21]: info.type==b'int8'
    Out[21]: array([ True, False,  True,  True, False], dtype=bool)
    

    【讨论】:

    • Ahhh ...我只是想查找字符数组所有元素前面的“b”是什么意思。这确实澄清了一些事情。是的,我正在使用 python 3。
    猜你喜欢
    • 2018-11-06
    • 2011-08-18
    • 2015-10-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2017-09-12
    相关资源
    最近更新 更多