2017-03-15 6 views
1

これは私が今使用しているコードです。私が使用するcsvfileは2つの列、1つはテキストで、もう1つは所属する会話の番号です。今では、テキストとは異なるngramを取得することができましたが、会話の数をngramに関連付けることもできます。だからngramがx回現れたら、どの会話に出てくるのか見たいのですが、どうすればいいですか?ngram計算後にデータフレームに余分な列を追加するには

import pandas as pd 
import numpy as np 
from sklearn.feature_extraction.text import CountVectorizer 


df = pd.read_csv("F:/textclustering/data/filteredtext1.csv", encoding="iso-8859-1" ,low_memory=False) 
document = df['Data'] 

vectorizer = CountVectorizer(ngram_range=(2, 2)) 
X = vectorizer.fit_transform(document) 
matrix_terms = np.array(vectorizer.get_feature_names()) 
matrix_freq = np.asarray(X.sum(axis=0)).ravel() 
terms = vectorizer.get_feature_names() 
freqs = X.sum(axis=0).A1 
dictionary = dict(zip(terms, freqs)) 
df = pd.DataFrame(dictionary,index=[0]).T.reindex() 
df.to_csv("F:/textclustering/data/terms2.csv", sep=',', na_rep="none") 

入力CSV

text, id 
example text is great, 1 
this is great, 2 
example text is great, 3 

所望の出力(またはこれに近いもの)

ngram, count, id 
example text, 2, [1,3] 
text is, 2, [1,3] 
is great, 3, [1,2,3] 
this is, 1, [1] 

答えて

1

まず、我々はその後、クー行列に変換するCSR疎行列に文書を変換しようとしています。 COOマトリックスを使用すると、スパース要素の行と列の位置を取得できます。

from itertools import groupby 
from sklearn.feature_extraction.text import CountVectorizer 

ls = [['example text is great', 1], 
     ['this is great', 2], 
     ['example text is great', 3]] 
document = [l[0] for l in ls] 
vectorizer = CountVectorizer(ngram_range=(2, 2)) 
X = vectorizer.fit_transform(document) 
X = X.tocoo() 

次に、(あなたが持っている各バイグラムの)列をgroupbyにすることができます。ここでは、タプルを最初に列で並べ替える必要がある小さなトリックがあります。次に、各行について、あなたのbigramによって行のインデックスを置き換えることができます。私はこの

[[0, 'example text', 2, [0, 2]], 
[1, 'is great', 3, [0, 1, 2]], 
[2, 'text is', 2, [0, 2]], 
[3, 'this is', 1, [1]]] 
のようになります。辞書名に id2vocab

output = [] 
id2vocab = dict((v,k) for k,v in vectorizer.vocabulary_.items()) 
zip_rc = sorted(zip(X.col, X.row), key=lambda x: x[0]) # group by column (vocab) 
count = np.ravel(X.sum(axis=0)) # simple sum column for count 
for g in groupby(zip_rc, key=lambda x: x[0]): 
    index = g[0] 
    bigram = id2vocab[index] 
    loc = [g_[1] for g_ in g[1]] 
    c = count[index] 
    output.append([index, bigram, c, loc]) 

出力を使用してマッピングを作成します

関連する問題