请给出一段利用python进行中文文本情感分析的代码
以下是一段利用Python进行中文文本情感分析的代码,使用了jieba分词和情感词典:
import jieba
import codecs
# 加载情感词典
posdict = []
with codecs.open('positive.txt', 'r', encoding='utf-8') as f:
for line in f.readlines():
posdict.append(line.strip())
negdict = []
with codecs.open('negative.txt', 'r', encoding='utf-8') as f:
for line in f.readlines():
negdict.append(line.strip())
# 分词并计算情感得分
def sentiment_score(text):
words = jieba.cut(text, cut_all=False)
pos_score = 0
neg_score = 0
for word in words:
if word in posdict:
pos_score += 1
elif word in negdict:
neg_score += 1
score = pos_score - neg_score
return score
# 测试情感分析函数
text = '今天天气真好,心情非常愉快。'
score = sentiment_score(text)
print(score) # 输出1,表示正面情感
text = '这部电影真的很烂,我完全不喜欢。'
score = sentiment_score(text)
print(score) # 输出-2,表示负面情感
需要注意的是,情感词典的选择和质量对情感分析的结果有很大的影响,因此需要选择合适的情感词典,并对其进行适当的调整和优化。另外,情感分析也可以使用机器学习等方法,但相应的代码会更加复杂
原文地址: http://www.cveoy.top/t/topic/cn1H 著作权归作者所有。请勿转载和采集!