emotion_analysis.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import json
  2. from tencentcloud.common import credential
  3. from tencentcloud.common.profile.client_profile import ClientProfile
  4. from tencentcloud.common.profile.http_profile import HttpProfile
  5. from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
  6. from tencentcloud.nlp.v20190408 import nlp_client, models
  7. def get_tencent_emotion_analysis(text, secret_id, secret_key):
  8. try:
  9. cred = credential.Credential(secret_id, secret_key)
  10. http_profile = HttpProfile()
  11. http_profile.endpoint = "nlp.tencentcloudapi.com"
  12. client_profile = ClientProfile()
  13. client_profile.httpProfile = http_profile
  14. client = nlp_client.NlpClient(cred, "ap-guangzhou", client_profile)
  15. req = models.SentimentAnalysisRequest()
  16. params = {
  17. "Text": text,
  18. "Flag": 2,
  19. "Mode": "2class"
  20. }
  21. req.from_json_string(json.dumps(params))
  22. resp = client.SentimentAnalysis(req)
  23. emotion_dict = json.loads(resp.to_json_string())
  24. return emotion_dict
  25. except TencentCloudSDKException as err:
  26. print(err)
  27. get_tencent_emotion_analysis('我很喜欢你!', 'AKIDlLfiU0FDuKUNyIL7bpmSrypPikUxGL9g', 'II1TeYAVZMs75mBJBl46qJVQ4RXLs9Au')