如何使用Scipy.io.loadmat将Matlab mat文件中的字符串数组加载到Python列表或元组中

Cau*_*ity 6 python arrays string matlab mat-file

我是Python新手的Matlab用户.我想在Matlab中将一个字符串的单元格数组写入Mat文件,并使用Python(可能是scipy.io.loadmat)将这个Mat文件加载到某个类似的类型中(例如字符串列表或字符串元组).但是loadmat将东西读入数组,我不知道如何将其转换为列表.我尝试了"tolist"函数,它不能像我预期的那样工作(我对Python数组或numpy数组的理解不够).例如:

Matlab代码:

cell_of_strings = {'thank',  'you', 'very', 'much'};
save('my.mat', 'cell_of_strings');
Run Code Online (Sandbox Code Playgroud)

Python代码:

matdata=loadmat('my.mat', chars_as_strings=1, matlab_compatible=1);
array_of_strings = matdata['cell_of_strings']
Run Code Online (Sandbox Code Playgroud)

然后,变量array_of_strings是:

array([[[[u't' u'h' u'a' u'n' u'k']], [[u'y' u'o' u'u']],
    [[u'v' u'e' u'r' u'y']], [[u'm' u'u' u'c' u'h']]]], dtype=object)
Run Code Online (Sandbox Code Playgroud)

我不知道如何将这个array_of_strings转换为Python列表或元组,以便它看起来像

list_of_strings = ['thank',  'you', 'very', 'much'];
Run Code Online (Sandbox Code Playgroud)

我不熟悉Python或numpy中的数组对象.我们将非常感谢您的帮助.

Mar*_*cin 5

你试过这个:

import scipy.io as si

a = si.loadmat('my.mat')
b = a['cell_of_strings']                # type(b) <type 'numpy.ndarray'>
list_of_strings  = b.tolist()           # type(list_of_strings ) <type 'list'>

print list_of_strings 
# output: [u'thank', u'you', u'very', u'much']
Run Code Online (Sandbox Code Playgroud)

  • b.tolist()给[[array([[u't',u'h',u'a',u'n',u'k']],dtype ='<U1'),数组([ [u'y',u'o',u'u']],dtype ='<U1'),array([[u'v',u'e',u'r',u'y'] ],dtype ='<U1'),数组([[u'm',u'u',u'c',u'h']],dtype ='<U1')]],似乎仍然是排列 (2认同)