python实现情感分析

本文介绍了一个使用Python的TextBlob库和百度翻译API实现的简单情感分析程序,通过输入文本,将其翻译成英文并分析其情感倾向(积极、消极或中立)。
摘要由CSDN通过智能技术生成

 `https://api.fanyi.baidu.com/doc/21`

首先我们要下载 textblob包,这是我们代码的关键

pip install textblob
from textblob import TextBlob
import requests
import random
from hashlib import md5

appid = 'xxxxx'
appkey = 'xxxxxxx'

#  `https://api.fanyi.baidu.com/doc/21`
from_lang = 'auto'
to_lang = 'en'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

def translate_text(query):
    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
    r = requests.post(url, params=payload, headers=headers)
    result = r.json()
    translations = [translation["dst"] for translation in result["trans_result"]]
    return translations

def analyze_sentiment(text):
    """分析情感倾向"""
    translations = translate_text(text)
    en_text = translations[0]
    if en_text:
        blob = TextBlob(en_text)
        sentiment = blob.sentiment

        polarity = sentiment.polarity
        subjectivity = sentiment.subjectivity

        if polarity > 0:
            result = 'positive'
        elif polarity < 0:
            result = 'negative'
        else:
            result = 'neutral'

        return result, polarity, subjectivity
    else:
        return None

if __name__ == '__main__':
    while True:
        input_text = input("请输入要分析的文本 (输入 'exit' 退出):")
        if input_text.lower() == 'exit':
            print("感谢使用,再见!")
            break
        result = analyze_sentiment(input_text)
        if result:
            sentiment, polarity, subjectivity = result
            print(f"情感倾向: {sentiment}, 极性: {polarity}, 主观性: {subjectivity}")
        else:
            print("翻译失败,请稍后重试。")

肥肠不错!

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值