Python 获取特定的类n-grams

Python 获取特定的类n-grams,python,nlp,n-gram,vocabulary,countvectorizer,Python,Nlp,N Gram,Vocabulary,Countvectorizer,我有一个tweet数据集,每个tweet标记为仇恨(1)或非仇恨(0)。我使用[3,4]个字符的n-grams单词包(sklearn的CountVectorizer)对数据进行了矢量化,我想为每个类提取最频繁的n-grams。下面的代码可以工作,但它概括了整个数据,而不是集中在类本身 bag_of_words = CountVectorizer( ngram_range =(3,4), analyzer='char' ) bag_of_words_mx = bag_of_wor

我有一个tweet数据集,每个tweet标记为仇恨(1)或非仇恨(0)。我使用[3,4]个字符的n-grams单词包(sklearn的CountVectorizer)对数据进行了矢量化,我想为每个类提取最频繁的n-grams。下面的代码可以工作,但它概括了整个数据,而不是集中在类本身

bag_of_words = CountVectorizer(
    ngram_range =(3,4),
    analyzer='char'
)

bag_of_words_mx = bag_of_words.fit_transform(X)

vocab = bag_of_words.vocabulary_
count_values = bag_of_words_mx.toarray().sum(axis=0)

# output n-grams
for ng_count, ng_text in sorted([(count_values[i],k) for k,i in vocab.items()]):
    if ng_count > 1:
        print(ng_count, ng_text)

有没有办法按类对词汇表进行排序?

试试
bag\u of theu words\u mx[y==0]
bag\u of theu words\u mx[y==1]
,其中
y
是包含目标变量的数组