2013-04-18 23 views

risposta

18

Se cv e il CountVectorizer e X è il corpus vettorizzati, quindi

zip(cv.get_feature_names(), 
    np.asarray(X.sum(axis=0)).ravel()) 

restituisce una lista di coppie (term, frequency) per ogni termine distinto nel corpus che il CountVectorizer estratta.

(Il piccolo asarray + ravel danza è necessaria per aggirare alcune stranezze nel scipy.sparse.)

+0

Grazie! Ma non sono ordinati, ma sono riuscito a farlo: per la tupla in ordine (occ_list, key = lambda idx: idx [1]): print tuple [0] + '' + str (tuple [1]). Il problema è che i caratteri åäö non vengono stampati. Ho impostato la codifica su utf8. – user1506145

+0

Sei sicuro che get_feature_names() avrà i termini ordinati in base al loro indice nella matrice frequenza-termine? Ho scoperto che cv.get_feature_names() e cv.vocabulary_.keys() non hanno lo stesso ordine. – user1506145

+3

@ user1506145: 'dict.keys' non garantisce alcun ordine; questo è esattamente il motivo per cui esiste get_feature_names'. –

0

Non v'è alcun built-in. Ho trovato un modo più veloce per farlo basa su Ando Saabas's answer:

from sklearn.feature_extraction.text import CountVectorizer 
texts = ["Hello world", "Python makes a better world"] 
vec = CountVectorizer().fit(texts) 
bag_of_words = vec.transform(texts) 
sum_words = bag_of_words.sum(axis=0) 
words_freq = [(word, sum_words[0, idx]) for word, idx in vec.vocabulary_.items()] 
sorted(words_freq, key = lambda x: x[1], reverse=True) 

uscita

[('world', 2), ('python', 1), ('hello', 1), ('better', 1), ('makes', 1)] 
Problemi correlati