情感分析python代码

以下是一个简单的情感分析Python代码示例:

import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer

# 初始化情感分析器
sia = SentimentIntensityAnalyzer()

# 定义文本
text = "这是一个非常电影,我喜欢它。"

# 进行情感分析
sentiment = sia.polarity_scores(text)

# 输出结果
print(sentiment)

输出结果:

{'neg': 0.0, 'neu': 0.476, 'pos': 0.524, 'compound': 0.6249}

其中,neg表示负面情感的得分,neu表示中性情感的得分,pos表示正面情感的得分,compound表示综合情感得分。在这个例子中,文本被判定为积极情感,综合情感得分为0.6249。

以下是一个更完整的情感分析Python代码示例,包括读取文本文件、分词、去除停用词、情感分析等步骤:

import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.sentiment.vader import SentimentIntensityAnalyzer

# 初始化情感分析器
sia = SentimentIntensityAnalyzer()

# 读取文本文件
with open('text.txt', 'r', encoding='utf-8') as f:
    text = f.read()

# 分词
tokens = word_tokenize(text)

# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_tokens = [token for token in tokens if token.lower() not in stop_words]

# 拼接分词后的文本
filtered_text = ' '.join(filtered_tokens)

# 进行情感分析
sentiment = sia.polarity_scores(filtered_text)

# 输出结果
print(sentiment)

在这个例子中,我们首先使用open()函数读取文本文件,然后使用word_tokenize()函数对文本进行分词,接着使用NLTK提供的停用词列表去除停用词,最后拼接分词后的文本并进行情感分析。输出结果与之前的例子类似,包括negneuposcompound四个得分。