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
    评论
Python可以通过许多不同的方式实现情感分析,其中最常用的是使用自然语言处理和机器学习技术。下面是一些实现情感分析的方式: 1.使用Python的自然语言处理库NLTK,它提供了许多用于文本处理和情感分析的工具和算法。 2.使用Python的机器学习库Scikit-learn,它提供了许多用于文本分类和情感分析的算法和模型。 3.使用Python的深度学习框架TensorFlow和PyTorch,它们提供了许多用于自然语言处理和情感分析的算法和模型。 4.使用Python的第三方情感分析库TextBlob和VADER,它们已经训练好了情感分析模型,并可以直接使用。 下面是一个使用Scikit-learn实现情感分析的例子: ```python from sklearn.feature_extraction.text import CountVectorizer from sklearn.naive_bayes import MultinomialNB from sklearn.pipeline import Pipeline # 训练数据 train_data = [ ("I love this sandwich.", "positive"), ("This is an amazing place!", "positive"), ("I feel very good about these beers.", "positive"), ("This is my best work.", "positive"), ("What an awesome view", "positive"), ("I do not like this restaurant", "negative"), ("I am tired of this stuff.", "negative"), ("I can't deal with this", "negative"), ("He is my sworn enemy!", "negative"), ("My boss is horrible.", "negative") ] # 创建模型 model = Pipeline([ ("vectorizer", CountVectorizer()), ("classifier", MultinomialNB()) ]) # 训练模型 model.fit([sample for sample in train_data], [sample for sample in train_data]) # 测试模型 test_sentence = "The beer was good." result = model.predict([test_sentence]) print(result) ``` 这个例子使用了一个朴素贝叶斯分类器来实现情感分析,训练数据是一些带有情感标记的句子。模型使用词袋模型来表示文本,然后使用朴素贝叶斯分类器进行分类。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值