python文本情感分析代码
时间: 2023-07-23 09:13:45 浏览: 40
以下是一段简单的Python文本情感分析代码,使用了NLTK库和情感词典。
首先,需要安装NLTK和情感词典。可以使用以下命令安装:
```
pip install nltk
```
下载情感词典:
```python
import nltk
nltk.download('vader_lexicon')
```
导入必要的库:
```python
from nltk.sentiment.vader import SentimentIntensityAnalyzer
```
创建情感分析器:
```python
analyzer = SentimentIntensityAnalyzer()
```
对文本进行情感分析:
```python
text = "I love this product, it's amazing!"
scores = analyzer.polarity_scores(text)
```
输出结果:
```python
{'neg': 0.0, 'neu': 0.278, 'pos': 0.722, 'compound': 0.6369}
```
结果包含四个值:neg(负向情感得分),neu(中性情感得分),pos(正向情感得分)和compound(综合情感得分)。
可以使用以下代码提取综合情感得分:
```python
compound_score = scores['compound']
```
根据综合情感得分来判断情感:
```python
if compound_score >= 0.05:
sentiment = 'Positive'
elif compound_score > -0.05 and compound_score < 0.05:
sentiment = 'Neutral'
else:
sentiment = 'Negative'
```
完整代码:
```python
import nltk
from nltk.sentiment.vader import SentimentIntensityAnalyzer
# download sentiment lexicon
nltk.download('vader_lexicon')
# create sentiment analyzer object
analyzer = SentimentIntensityAnalyzer()
# analyze sentiment of text
text = "I love this product, it's amazing!"
scores = analyzer.polarity_scores(text)
compound_score = scores['compound']
# determine sentiment based on compound score
if compound_score >= 0.05:
sentiment = 'Positive'
elif compound_score > -0.05 and compound_score < 0.05:
sentiment = 'Neutral'
else:
sentiment = 'Negative'
print(sentiment)
```