情感分析调用因认知服务而失败,返回“ HttpOperationError”

时间:2019-11-04 08:14:28

标签: sentiment-analysis microsoft-cognitive

text_analytics = TextAnalyticsClient(endpoint=endpoint, credentials=credentials)
documents = [
    {
        "id": "1",
        "language": "en",
        "text": "I had the best day of my life."
    }
]
response = text_analytics.sentiment(documents=documents)
for document in response.documents:
    print("Document Id: ", document.id, ", Sentiment Score: ",
          "{:.2f}".format(document.score))

您好,请参考API手册https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quickstarts/python-sdk#sentiment-analysis中的示例代码  尝试调用情感分类器时出现以下错误


HttpOperationError                        Traceback (most recent call last)
<ipython-input-18-f0fb322c9e8c> in <module>
      8     }
      9 ]
---> 10 response = text_analytics.sentiment(documents=documents)
     11 for document in response.documents:
     12     print("Document Id: ", document.id, ", Sentiment Score: ",

~/anaconda3/envs/lib/python3.6/site-packages/azure/cognitiveservices/language/textanalytics/text_analytics_client.py in sentiment(self, show_stats, documents, custom_headers, raw, **operation_config)
    361 
    362         if response.status_code not in [200, 500]:
--> 363             raise HttpOperationError(self._deserialize, response)
    364 
    365         deserialized = None

HttpOperationError: Operation returned an invalid status code 'Resource Not Found'

1 个答案:

答案 0 :(得分:1)

它对我很有效,请按照以下步骤操作或检查以下步骤,以开始使用python情感分析SDK:

  1. 在Azure门户上创建文本分析服务: enter image description here

  2. 创建后,记下其端点和两个键之一。 enter image description here

  3. 尝试以下代码:

from azure.cognitiveservices.language.textanalytics import TextAnalyticsClient
from msrest.authentication import CognitiveServicesCredentials

subscriptionKey = "<your Azure servcice key >"
endpoint = "<your Azure servcice endpoint>"


credentials = CognitiveServicesCredentials(subscriptionKey)

text_analytics = TextAnalyticsClient(endpoint=endpoint, credentials=credentials)

documents = [
    {
        "id": "1",
        "language": "en",
        "text": "I had the best day of my life."
    }
]
response = text_analytics.sentiment(documents=documents)
for document in response.documents:
    print("Document Id: ", document.id, ", Sentiment Score: ",
          "{:.2f}".format(document.score))

结果:

enter image description here

希望有帮助。