python基于情感词典进行情感分析的代码
时间: 2023-08-31 11:13:24 浏览: 188
Python实现的基于规则词典的中文情感极性分析工具源代码,基于知网、清华、BosonNLP情感词典,易扩展,基准方法,开箱即用
5星 · 资源好评率100%
以下是一段基于情感词典的Python情感分析代码。使用情感词典可以将文本中的每个单词与情感极性相关联,然后计算每个单词的情感极性得分并对得分进行加权平均,从而得出整个文本的情感极性。
首先,需要下载并导入情感词典。这里使用的是NTUSD情感词典,可以从以下链接下载并解压缩:
http://www.nlg.csie.ntu.edu.tw/nlpresource/NTUSD-Fin/NTUSD-Fin.zip
然后读取情感词典文件并将每个单词与情感极性相关联:
```python
def read_sentiment_dict(filename):
sentiment_dict = {}
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
tokens = line.strip().split('\t')
word = tokens[0]
sentiment = int(tokens[1])
sentiment_dict[word] = sentiment
return sentiment_dict
filename = 'NTUSD-Fin/NTUSD_positive_negative_simplified.txt'
sentiment_dict = read_sentiment_dict(filename)
```
接下来,可以定义一个函数来计算文本的情感极性得分。该函数将文本分成单词,并对每个单词计算情感极性得分,然后将得分进行加权平均:
```python
def calculate_sentiment(text, sentiment_dict):
words = text.split()
sentiment_scores = []
for word in words:
if word in sentiment_dict:
sentiment_scores.append(sentiment_dict[word])
if len(sentiment_scores) > 0:
sentiment_score = sum(sentiment_scores) / len(sentiment_scores)
else:
sentiment_score = 0
return sentiment_score
```
最后,可以使用该函数来计算文本的情感极性得分,并根据得分来判断情感:
```python
text = "I love this product, it's amazing!"
sentiment_score = calculate_sentiment(text, sentiment_dict)
if sentiment_score > 0:
sentiment = 'Positive'
elif sentiment_score == 0:
sentiment = 'Neutral'
else:
sentiment = 'Negative'
print(sentiment)
```
完整代码:
```python
def read_sentiment_dict(filename):
sentiment_dict = {}
with open(filename, 'r', encoding='utf-8') as f:
for line in f:
tokens = line.strip().split('\t')
word = tokens[0]
sentiment = int(tokens[1])
sentiment_dict[word] = sentiment
return sentiment_dict
def calculate_sentiment(text, sentiment_dict):
words = text.split()
sentiment_scores = []
for word in words:
if word in sentiment_dict:
sentiment_scores.append(sentiment_dict[word])
if len(sentiment_scores) > 0:
sentiment_score = sum(sentiment_scores) / len(sentiment_scores)
else:
sentiment_score = 0
return sentiment_score
filename = 'NTUSD-Fin/NTUSD_positive_negative_simplified.txt'
sentiment_dict = read_sentiment_dict(filename)
text = "I love this product, it's amazing!"
sentiment_score = calculate_sentiment(text, sentiment_dict)
if sentiment_score > 0:
sentiment = 'Positive'
elif sentiment_score == 0:
sentiment = 'Neutral'
else:
sentiment = 'Negative'
print(sentiment)
```
阅读全文