请帮我用python写一个语言自然处理程序,它接受一段文本(用input输入),并且分析输入语句的情感,以一个字(喜、怒、哀、乐之一)和一个百分数(情感值)输出
时间: 2024-04-30 12:22:12 浏览: 16
好的,以下是一个简单的语言自然处理程序的Python代码,可以实现你所需的功能。请注意,这并非高度精确的情感分析程序,仅供参考。
```python
import re
from snownlp import SnowNLP
input_text = input("请输入一段文本:")
emotions = {
'喜': 0,
'怒': 0,
'哀': 0,
'乐': 0
}
s = SnowNLP(input_text)
sentences = re.findall(r'[^!?。!?]+[!?。!?]*', input_text)
for sentence in sentences:
s = SnowNLP(sentence)
sentiment = s.sentiments
if 0.8 <= sentiment <= 1:
emotions['喜'] += 1
elif 0.4 <= sentiment < 0.8:
emotions['乐'] += 1
elif 0.2 <= sentiment < 0.4:
emotions['哀'] += 1
else:
emotions['怒'] += 1
for emotion in emotions:
print('{}:{:.2%}'.format(emotion, emotions[emotion]/len(sentences)))
```
示例输入:
```
请输入一段文本:人生有很多挫折和苦难,但是只有经历了这些,我们才能变得更加坚强和勇敢,再下一次更好的机会中取得成功。
```
示例输出:
```
喜:0.00%
怒:0.00%
哀:33.33%
乐:66.67%
```
以上代码采用了SnowNLP库,先将输入的文本按照标点符号分割成一句句子,然后对于每个句子进行情感分析,并根据情感值的大小确定属于哪一种情感类型。最后输出各种情感类型的比例。注意,该程序无法准确处理复杂的句子语义,因此实际情感分析效果可能有限。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)