怎么用情感词典进行情感分析,举个代码例子
时间: 2023-12-03 19:45:15 浏览: 33
情感词典是一种常用的情感分析方法,其基本思想是将文本中的情感词汇与一个情感词典进行匹配,从而判断文本的情感倾向。
下面是一个 Python 代码例子,使用了中文情感词典“知网情感词典”进行情感分析:
```python
import codecs
# 加载情感词典
def load_dict(filename):
dict = {}
with codecs.open(filename, 'r', 'utf-8') as f:
for line in f:
words = line.strip().split()
if len(words) > 1:
dict[words[0]] = int(words[1])
return dict
posdict = load_dict('positive.txt') # 正向情感词典
negdict = load_dict('negative.txt') # 负向情感词典
# 对文本进行情感分析
def sentiment_score(text, posdict, negdict):
words = text.strip().split()
pos_score = 0
neg_score = 0
for word in words:
if word in posdict:
pos_score += posdict[word]
elif word in negdict:
neg_score += negdict[word]
return pos_score, neg_score
text = "我很高兴今天能见到你"
pos_score, neg_score = sentiment_score(text, posdict, negdict)
print("正向情感得分:", pos_score)
print("负向情感得分:", neg_score)
```
以上代码将文本中的每个词与情感词典进行匹配,如果是正向情感词则加上对应的得分,如果是负向情感词则减去对应的得分。最终的得分即为文本的情感倾向得分。