写出基于情感词典的情感分析代码 
时间: 2023-03-31 16:05:01 浏览: 69
以下是基于情感词典的情感分析代码示例:
```
import jieba
import codecs
# 加载情感词典
posdict = []
negdict = []
with codecs.open('posdict.txt', 'r', 'utf-8') as f:
for line in f:
posdict.append(line.strip())
with codecs.open('negdict.txt', 'r', 'utf-8') as f:
for line in f:
negdict.append(line.strip())
# 分词并统计情感词汇
def sentiment(text):
words = jieba.cut(text)
poscount =
negcount =
for word in words:
if word in posdict:
poscount += 1
elif word in negdict:
negcount += 1
if poscount > negcount:
return 'positive'
elif poscount < negcount:
return 'negative'
else:
return 'neutral'
```
以上代码中,我们首先加载了情感词典,然后定义了一个 sentiment 函数,该函数接受一段文本作为输入,使用 jieba 分词工具将文本分词,并统计其中的情感词汇。如果正向情感词汇的数量大于负向情感词汇的数量,则返回 positive;如果负向情感词汇的数量大于正向情感词汇的数量,则返回 negative;否则返回 neutral。
相关推荐













