统计词性标记模式的出现次数

2024-05-23 13:17:39 发布

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

因此,我对数据框中的一列应用了词性标记。对于每一个句子,我想计算这个模式的出现次数:NNP,MD,VB

例如,我有以下句子: 委托人和承包商之间的通信应使用英语

词性标注将是: (通讯,NNS),(在,在),(在,在),(在,DT),(委托人,NNP),(和,CC),(在,DT),(承包商,NNP),(应,MD),(be,VB),(在,DT),(在,DT),(英语,JJ),(语言,NN)

请注意,在词性标记结果中,模式(NNP、MD、VB)存在并出现1次。我想在df中为这些事件创建一个新列

你知道我该怎么做吗

提前谢谢


Tags: 数据标记dt模式be次数md句子
1条回答
网友
1楼 · 发布于 2024-05-23 13:17:39

一个简单的计数器功能将执行您想要的

输入:

df = pd.DataFrame({'POS':['(communications, NNS), (between,IN), (the, DT), (Principal, NNP), (and, CC), (the, DT), (Contractor, NNP), (shall, MD), (be,VB), (in, DT), (the, DT), (English, JJ), (language, NN)', '(Contractor, NNP), (shall, MD), (be,VB), (communications, NNS), (between,IN), (the, DT), (Principal, NNP), (and, CC), (the, DT), (Contractor, NNP), (shall, MD), (be,VB), (in, DT), (the, DT), (English, JJ), (language, NN)', '(and, CC), (the, DT)']})

功能:

def counter(pos):
    words, tags = [], []
    for item in pos.split('), ('):
        temp = item.strip(' )(')
        word, tag = temp.split(',')[0], temp.split(',')[-1].strip()
        words.append(word); tags.append(tag)
    length = len(tags)
    if length<3:
        return 0
    count = 0
    for idx in range(length):
        if tags[idx:idx+3]==['NNP', 'MD', 'VB']:
            count+=1
    return count

输出:

df['occ'] = df['POS'].apply(counter)
df

    POS     occ
0   (communications, NNS), (between,IN), (the, DT)...   1
1   (Contractor, NNP), (shall, MD), (be,VB), (comm...   2
2   (and, CC), (the, DT)    0

相关问题 更多 >