数据帧的计数器对象仅包括第一种情况

2024-04-29 00:50:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将计数器对象列表转换为数据帧。 假设我有以下计数器输出:

Counter({''VERB': 19, 'PRON': 15, 'NOUN': 13, '.': 9, 'ADP': 9, 'DET': 7, 'ADJ': 4, 'PRT': 4, 'CONJ': 3, 'ADV': 3, 'NUM': 2, 'x': 0})
Counter({''VERB': 14, 'NOUN': 9, 'ADV': 8, 'PRON': 8, 'ADJ': 7, '.': 6, 'CONJ': 4, 'DET': 3, 'ADP': 3, 'PRT': 2, 'x': 0, 'NUM': 0})

我想把它转换成一个数据帧。但是,当尝试执行此操作时,它只包含第一个计数器对象,因此不会迭代另一个计数器对象(或者使用其他计数器对象迭代文档的其余部分)

index   NOUN    VERB    ADJ .   ADP PRON    DET CONJ    ADV PRT NUM x
0       13      19      4   9   9   15      7   3       3   4   2   0

下面你可以找到我用过的脚本。我想我错过了一个小细节,但似乎错过了它

import nltk
import pandas as pd

for line in lines:
    tokens = nltk.word_tokenize(line)
    tagged = nltk.pos_tag(tokens, tagset='universal')
    selective_tagged = ['ADJ','ADP','ADV','CONJ','DET','NOUN','NUM','PRT','PRON','VERB', '.', 'x']
    selective_tagged_words =[]
    for word,tag in tagged:
        if tag in selective_tagged:
            selective_tagged_words.append((word,tag))
    counts=Counter(tag for word,tag in selective_tagged_words)
    other_tags = set(selective_tagged)-set(counts)
    for i in other_tags:
        counts[i]=0
    df = pd.DataFrame.from_dict(counts, orient='index').reset_index()   
    df = df.T 
    postag.append(counts)

提前谢谢


Tags: 对象intag计数器prtnoundetselective