当前位置:   article > 正文

python实现情感分析_python编写代码对文本进行情感分析

python编写代码对文本进行情感分析

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

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

pip install textblob
  1. from textblob import TextBlob
  2. import requests
  3. import random
  4. from hashlib import md5
  5. appid = 'xxxxx'
  6. appkey = 'xxxxxxx'
  7. # `https://api.fanyi.baidu.com/doc/21`
  8. from_lang = 'auto'
  9. to_lang = 'en'
  10. endpoint = 'http://api.fanyi.baidu.com'
  11. path = '/api/trans/vip/translate'
  12. url = endpoint + path
  13. def make_md5(s, encoding='utf-8'):
  14. return md5(s.encode(encoding)).hexdigest()
  15. def translate_text(query):
  16. salt = random.randint(32768, 65536)
  17. sign = make_md5(appid + query + str(salt) + appkey)
  18. headers = {'Content-Type': 'application/x-www-form-urlencoded'}
  19. payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}
  20. r = requests.post(url, params=payload, headers=headers)
  21. result = r.json()
  22. translations = [translation["dst"] for translation in result["trans_result"]]
  23. return translations
  24. def analyze_sentiment(text):
  25. """分析情感倾向"""
  26. translations = translate_text(text)
  27. en_text = translations[0]
  28. if en_text:
  29. blob = TextBlob(en_text)
  30. sentiment = blob.sentiment
  31. polarity = sentiment.polarity
  32. subjectivity = sentiment.subjectivity
  33. if polarity > 0:
  34. result = 'positive'
  35. elif polarity < 0:
  36. result = 'negative'
  37. else:
  38. result = 'neutral'
  39. return result, polarity, subjectivity
  40. else:
  41. return None
  42. if __name__ == '__main__':
  43. while True:
  44. input_text = input("请输入要分析的文本 (输入 'exit' 退出):")
  45. if input_text.lower() == 'exit':
  46. print("感谢使用,再见!")
  47. break
  48. result = analyze_sentiment(input_text)
  49. if result:
  50. sentiment, polarity, subjectivity = result
  51. print(f"情感倾向: {sentiment}, 极性: {polarity}, 主观性: {subjectivity}")
  52. else:
  53. print("翻译失败,请稍后重试。")

肥肠不错!

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号