怎么使用snowNLP对.txt文件里的评论进行情感分析python
时间: 2024-05-10 13:15:28 浏览: 82
使用 `snowNLP` 进行情感分析需要先安装该库,可以使用 `pip` 进行安装:
```
pip install snownlp
```
下面是对 `.txt` 文件进行情感分析的步骤:
1. 导入 `snownlp` 库和打开 `.txt` 文件:
```python
import codecs
from snownlp import SnowNLP
with codecs.open('comments.txt', 'r', encoding='utf-8') as f:
comments = f.readlines()
```
2. 对每条评论进行情感分析,统计正面和负面评论的数量:
```python
n_positive = 0
n_negative = 0
for comment in comments:
s = SnowNLP(comment)
if s.sentiments > 0.5:
n_positive += 1
else:
n_negative += 1
```
3. 计算正面评论和负面评论的比例:
```python
positive_ratio = n_positive / len(comments)
negative_ratio = n_negative / len(comments)
print('正面评论比例:{:.2%}'.format(positive_ratio))
print('负面评论比例:{:.2%}'.format(negative_ratio))
```
完整代码如下:
```python
import codecs
from snownlp import SnowNLP
with codecs.open('comments.txt', 'r', encoding='utf-8') as f:
comments = f.readlines()
n_positive = 0
n_negative = 0
for comment in comments:
s = SnowNLP(comment)
if s.sentiments > 0.5:
n_positive += 1
else:
n_negative += 1
positive_ratio = n_positive / len(comments)
negative_ratio = n_negative / len(comments)
print('正面评论比例:{:.2%}'.format(positive_ratio))
print('负面评论比例:{:.2%}'.format(negative_ratio))
```
阅读全文