Press "Enter" to skip to content

Asent库 | 英文文本数据情感分析

 

Asent 是一个新的Python情感分析库, 依据情感词典,按照一定的规则,可用于评判词语、句子、文档的情感信息(正、负)。

 

目前情感计算规则有

 

否定(即“不高兴”)

 

加强词(“非常高兴”)

 

对比共轭(即“但是”)

 

其他强调标记,如感叹号、大小写和问号。

 

Asent目前仅支持 英语、丹麦、挪威、瑞典4种语言

 

参考往期文章  建议收藏 | nltk和spacy配置方法 需要先下载并配置spacy模型 。 以下将带您逐步了解情绪是如何计算的。

 

!pip3 install spacy==3.2.0
!pip3 install asent==0.4.2

 

首先,我们需要一个 spaCy 管道,并且我们需要向其中添加 asent 管道。

 

import asent
import spacy
# en_core_web_lg是spacy模型,需要单独下载&配置,本文代码才可使用
nlp = spacy.load("en_core_web_lg")
# add the rule-based sentiment model
nlp.add_pipe("asent_en_v1")

 

<asent.component.Asent at 0x7fd6b3243130>

 

效价和极性

 

如下所示, token的效价信息来自于人工标注的词典。例如 I am not very happy 中词语 happy 的人类情感评分是2.7。

 

token_polarity.png)

 

首先我们查看每个词语对应的效价。

 

doc = nlp("I am not very happy.")
for token in doc:
    print(token, "\t", token._.valence)

 

I  0.0
am  0.0
not  0.0
very  0.0
happy  2.7
.  0.0

 

在该语境中, happy 前面有否定词not修饰,所以情感极性方面应该被看做消极的。一般否定词和副词可以将形容词的情感进行反转和放大(缩小)。

 

for token in doc:
    print(token._.polarity)

 

polarity=0.0 token=I span=I
polarity=0.0 token=am span=am
polarity=0.0 token=not span=not
polarity=0.0 token=very span=very
polarity=-2.215 token=happy span=not very happy
polarity=0.0 token=. span=.

 

注意到, 词语在 happy 拥有-2.215的极性分,该分是由 not very happy 确定的。

 

可视化

 

asent拥有多种情感极性可视化的方法

 

asent.visualize(doc,)

 

 

asent.visualize(doc,)

 

for sentence in doc.sents:
    print(sentence._.polarity)

 

neg=0.391 neu=0.609 pos=0.0 compound=-0.4964 span=I am not very happy.

 

doc._.polarity

 

DocPolarityOutput(neg=0.391, neu=0.609, pos=0.0, compound=-0.4964)

 

doc2 = nlp("I am not very happy.I am very very happy.It is awesome!!")
print('doc2情感极性信息: ', doc2._.polarity)
print()
print('doc2情感得分:', doc2._.polarity.compound)

 

doc2情感极性信息:  neg=0.13 neu=0.536 pos=0.333 compound=0.2794
doc2情感得分: 0.279353567721562

 

#每个句子的情感极性信息
for sentence in doc2.sents:
    print(sentence._.polarity)

 

neg=0.391 neu=0.609 pos=0.0 compound=-0.4964 span=I am not very happy.
neg=0.0 neu=0.539 pos=0.461 compound=0.6453 span=I am very very happy.
neg=0.0 neu=0.461 pos=0.539 compound=0.6892 span=It is awesome!!

 

#每个句子的情感得分
for sentence in doc2.sents:
    print(sentence._.polarity.compound)

 

-0.4964238981617178
0.6452764659402158
0.689208135386188

 

出处:大邓和他的Python

https://hidadeng.github.io/blog/

Be First to Comment

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注