以下是一段利用python进行中文文本情感分析的代码,利用了哈工大的情感词典:

# -*- coding: utf-8 -*-

import jieba
import re

# 加载情感词典
sentiment_dict = {}
with open('sentiment_dict.txt', 'r', encoding='utf-8') as f:
    for line in f:
        word, score = line.strip().split('\t')
        sentiment_dict[word] = int(score)

# 分词并去除停用词
def cut_words(text):
    stopwords = set(['的', '了', '是', '我', '你', '他', '她', '们', '在', '有', '和', '就', '不', '这', '也', '都', '上', '下', '中'])
    words = [word for word in jieba.cut(text) if word not in stopwords]
    return words

# 计算情感得分
def get_sentiment_score(text):
    words = cut_words(text)
    score = 0
    for word in words:
        if word in sentiment_dict:
            score += sentiment_dict[word]
    return score

if __name__ == '__main__':
    text = '今天天气真好,心情非常愉悦'
    score = get_sentiment_score(text)
    print('情感得分为:', score)

其中,sentiment_dict.txt为情感词典文件,每行格式为词语\t情感得分,其中情感得分为1表示积极情感,为-1表示消极情感,为0表示中性情感。cut_words函数用于分词并去除停用词,get_sentiment_score函数用于计算情感得分。在测试时,我们可以将要分析的文本传入get_sentiment_score函数中,即可得到情感得分。在本例中,输出的情感得分为2,表示积极情感

请给出一段利用python进行中文文本情感分析的代码并且需要用到情感词典

原文地址: https://www.cveoy.top/t/topic/cn4i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录