2011-01-27 13 views
6

Sono un utente Matlab nuovo di Python. Vorrei scrivere un array di celle di stringhe in Matlab in un file Mat e caricare questo file Mat usando Python (magari scipy.io.loadmat) in un tipo simile (ad esempio, elenco di stringhe o tupla di stringhe). Ma loadmat legge le cose in array e non sono sicuro di come convertirlo in una lista. Ho provato la funzione "tolist" che non funziona come mi aspettavo (ho una scarsa comprensione dell'array Python o dell'array numpy). Ad esempio: il codiceCome caricare l'array di celle di stringhe nei file Matlab mat nell'elenco Python o tuple usando Scipy.io.loadmat

Matlab: codice

cell_of_strings = {'thank', 'you', 'very', 'much'}; 
save('my.mat', 'cell_of_strings'); 

Python:

matdata=loadmat('my.mat', chars_as_strings=1, matlab_compatible=1); 
array_of_strings = matdata['cell_of_strings'] 

Poi, i array_of_strings variabile è:

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) 

io non sono sicuro di come convertire questo array_of_strings in una lista Python o tupla in modo che assomigli a

list_of_strings = ['thank', 'you', 'very', 'much']; 

Non ho familiarità con l'oggetto array in Python o numpy. Il tuo aiuto sarà molto apprezzato.

risposta

4

Rivolgersi ai provato questo:

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'] 
+2

b.tolist() restituisce [[matrice ([[u't ', u'h', u'a ', u'n', u'k ']], dtype =' Causality

+0

@Denzel. Devi usare chars_as_strings = 1, matlab_compatible = 1? – Marcin

2

Questo appare come un lavoro per list comprehension. Ripetendo il tuo esempio, ho fatto questo in MATLAB:

cell_of_strings = {'thank', 'you', 'very', 'much'}; 
save('my.mat', 'cell_of_strings','-v7'); 

sto usando una nuova versione di MATLAB, che salva i file in formato .mat HDF5 per impostazione predefinita. loadmat non è in grado di leggere i file HDF5, quindi il flag '-v7' è quello di forzare MATLAB a salvare in una versione precedente il file .mat, che può comprendere loadmat.

In Python, ho caricato la matrice cellulare proprio come hai fatto:

import scipy.io as sio 
matdata = sio.loadmat('%s/my.mat' %path, chars_as_strings=1, matlab_compatible=1); 
array_of_strings = matdata['cell_of_strings'] 

stampa array_of_strings dà:

[[array([[u't', u'h', u'a', u'n', u'k']], 
      dtype='<U1') 
     array([[u'y', u'o', u'u']], 
      dtype='<U1') 
     array([[u'v', u'e', u'r', u'y']], 
      dtype='<U1') 
     array([[u'm', u'u', u'c', u'h']], 
      dtype='<U1')]] 

La variabile array_of_strings è una (1,4) matrice di oggetti numpy ma ci gli array sono annidati all'interno di ciascun oggetto. Ad esempio, il primo elemento di array_of_strings è un (1,5) array contenente le lettere per "thank". Cioè,

array_of_strings[0,0] 
array([[u't', u'h', u'a', u'n', u'k']], 
     dtype='<U1') 

per arrivare alla prima lettera 't', devi fare qualcosa di simile:

array_of_strings[0,0][0,0] 
u't' 

Dal momento che abbiamo a che fare con gli array nidificati, abbiamo bisogno di impiegare qualche tecnica ricorsiva per estrai i dati, ovvero i cicli nidificati for. Ma prima, ti mostrerò come estrarre la prima parola:

first_word = [str(''.join(letter)) for letter in array_of_strings[0][0]] 
first_word 
['thank'] 

Qui sto usando una lista di comprensione. Fondamentalmente, eseguo il ciclo di ciascuna lettera in array_of_strings [0] [0] e concatenandoli utilizzando il metodo ''.join. La funzione string() consiste nel convertire le stringhe Unicode in stringhe regolari.

Ora, per ottenere le stringhe della lista che si desidera, abbiamo solo bisogno di scorrere ogni matrice di lettere:

words = [str(''.join(letter)) for letter_array in array_of_strings[0] for letter in letter_array] 
words 
['thank', 'you', 'very', 'much'] 

di lista richiedere un certo tempo per abituarsi, ma sono estremamente utili. Spero che questo ti aiuti.

+0

words = [str (''. Join (lettera)) per letter_array in array_of_strings [0] per lettera in letter_array] dovrebbe essere words = [str (''. Join (lettera)) per letter_array in array_of_strings per lettera in letter_array] –

Problemi correlati