这是我现在的代码,我使用的csvfile有两列,一列是文本,另一列是它所属会话的编号。现在我已经设法从文本中得到了不同的ngram,但是我还想知道与ngram相关的对话的数量。所以如果一个ngram出现了x次,我想看看它出现在哪些对话中。我该怎么做?
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
^{pr2}$期望输出(或接近此值的输出)
ngram, count, id
example text, 2, [1,3]
text is, 2, [1,3]
is great, 3, [1,2,3]
this is, 1, [1]
首先,我们要把文档转换成csr稀疏矩阵,然后再转换成coo矩阵。COO矩阵允许您获得稀疏元素的行和列的位置。在
然后您可以按列分组(对于您拥有的每个bigram)。这里有一个小技巧,首先必须按列对元组进行排序。然后,对于每一行,可以用您的bigram替换行中的索引。我使用dictionary name
^{pr2}$id2vocab
创建映射输出如下所示
相关问题 更多 >
编程相关推荐