首页 > 解决方案 > NLTK:同现矩阵

问题描述

我已经预处理了一个评论数据集并对其进行了标记。这是df的样子: 在此处输入图像描述

然后我从列中创建两个列表:

cent_vocab - 包含前 1000 个最常用的名词(中心词)

cont_vocab - 包含前 1000 个最常用的动词/形容词(上下文词)

使用这两个 1,000 词的词汇表,我想创建一个共现矩阵,在该矩阵中,对于每个中心词,您可以跟踪有多少上下文词与它同时出现。以这个只有一个句子的简短评论为例,我们希望获得中心词餐厅的动词和形容词的共现:

一个。'餐厅提供美味佳肴' </p>

{'餐厅':{'大':2,'服务':1,'美味':1}}

lower_tagged列包含大约 95,000 行

def get_coocs(df, cent_vocab, cont_vocab):
    coocs = {} 
    reviews = df["tokenized"]
    for cent in cent_vocab:
        cont_coocs = {}
        for review in reviews:
            if cent in review:
                for cont in cont_vocab:
                    if cont in review:
                        if cont in cont_coocs:
                            cont_coocs[cont] += 1
                        else:
                            cont_coocs[cont] = 1
                    else:
                        cont_coocs[cont] = 0
 
        coocs[cent] = cont_coocs
    return coocs 

但是,我的上述功能失败了。我的输出是空的,如下所示: 在此处输入图像描述

标签: pythonpandasnlpnltk

解决方案


推荐阅读