2016-11-22 19 views
0

我有一個帶有5個文檔的文本語料庫,每個文檔之間用/ n分隔。我想爲文檔中的每個單詞提供一個id並計算其各自的tfidf分數。 例如,假設我們有一個名爲「corpus.txt」文本語料庫如下: -將文本語料庫轉換爲帶有vocabulary_id和tfidf分數的文本文檔

「堆棧 過流 文本量化scikit 蟒蛇SciPy的稀疏CSR」 在計算使用

mylist =list("corpus.text") 
vectorizer= CountVectorizer 
x_counts = vectorizer_train.fit_transform(mylist) 
tfidf_transformer = TfidfTransformer() 
x_tfidf = tfidf_transformer.fit_transform(x_counts) 
的TFIDF

輸出是

(0,12) 0.1234 #for 1st document 
(1,8) 0.3456 #for 2nd document 
(1,4) 0.8976 
(2,15) 0.6754 #for third document 
(2,14) 0.2389 
(2,3) 0.7823 
(3,11) 0.9897 #for fourth document 
(3,13) 0.8213 
(3,5) 0.7722 
(3,6) 0.2211 
(4,7) 0.1100 # for fifth document 
(4,10) 0.6690 
(4,2) 0.0912 
(4,9) 0.2345 
(4,1) 0.1234 

我轉換這個scipy.sparse.csr矩陣成列表的列表刪除的文檔ID,並且k eeping僅使用vocabulary_id及其相應tfidf得分:

m = x_tfidf.tocoo() 
mydata = {k: v for k, v in zip(m.col, m.data)} 
key_val_pairs = [str(k) + ":" + str(v) for k, v in mydata.items()] 

但問題是,我正在其中vocabulary_id及其相應tfidf分數以升序排列,沒有任何關於文件的輸出。

例如,對於上面給出的語料庫我的電流輸出(我丟到使用文本文件JSON)看起來像:

1:0.1234 
2:0.0912 
3:0.7823 
4:0.8976 
5:0.7722 
6:0.2211 
7:0.1100 
8:0.3456 
9:0.2345 
10:0.6690 
11:0.9897 
12:0.1234 
13:0.8213 
14:0.2389 
15:0.6754 

,而我會想我的文本文件,要像如下:

12:0.1234 
8:0.3456 4:0.8976 
15:0.1234 14:0.2389 3:0.7823 
11:0.9897 13:0.8213 5:0.7722 6:0.2211 
7:0.1100 10:0.6690 2:0.0912 9:0.2345 1:0.1234 

任何想法如何完成它?

+0

我已經回答了你的問題,希望他會lp你! –

回答

1

我想這是你需要的。這裏corpus是一個文件集合。

from sklearn.feature_extraction.text import TfidfVectorizer 
corpus = ["stack over flow stack over flow text vectorization scikit", "stack over flow"] 

vectorizer = TfidfVectorizer() 
x = vectorizer.fit_transform(corpus) # corpus is a collection of documents 

print(vectorizer.vocabulary_) # vocabulary terms and their index 
print(x) # tf-idf weights for each terms belong to a particular document 

此打印:

{'vectorization': 5, 'text': 4, 'over': 1, 'flow': 0, 'stack': 3, 'scikit': 2} 
    (0, 2) 0.33195438857 # first document, word = scikit 
    (0, 5) 0.33195438857 # word = vectorization 
    (0, 4) 0.33195438857 # word = text 
    (0, 0) 0.472376562969 # word = flow 
    (0, 1) 0.472376562969 # word = over 
    (0, 3) 0.472376562969 # word = stack 
    (1, 0) 0.57735026919 # second document 
    (1, 1) 0.57735026919 
    (1, 3) 0.57735026919 

從這些信息中,你可以代表你想要的方式的文件如下:

cx = x.tocoo() 
doc_id = -1 
for i,j,v in zip(cx.row, cx.col, cx.data): 
    if doc_id == -1: 
     print(str(j) + ':' + "{:.4f}".format(v), end=' ') 
    else: 
     if doc_id != i: 
      print() 
     print(str(j) + ':' + "{:.4f}".format(v), end=' ') 
    doc_id = i 

此打印:

2:0.3320 5:0.3320 4:0.3320 0:0.4724 1:0.4724 3:0.4724 
0:0.5774 1:0.5774 3:0.5774 
+0

你好, 對不起,延遲迴復。 您的解決方案正是我所需要的。 我想問我是否需要排序輸出,那我應該如何完成它? – Saurabh