以下是一段利用 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('	')
        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/nuHY 著作权归作者所有。请勿转载和采集!

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