使用天蓝色错误“找不到资源”进行情感分析

时间:2019-12-05 06:41:04

标签: python azure sentiment-analysis microsoft-cognitive azure-cognitive-services

我创建了一个Python程序,该程序接受String作为输入并对其进行情感分析。

我已经按照文档中的说明创建了环境变量,并重新启动了cmd以及Visual Studio,但是仍然出现以下错误:

  

遇到异常。操作返回了无效的状态码“找不到资源”

python程序如下:

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

#TEXT_ANALYTICS_SUBSCRIPTION_KEY = 'b2c4f0ee35c941078d9e6971c15c3472'
#TEXT_ANALYTICS_ENDPOINT = 'https://westcentralus.api.cognitive.microsoft.com/text/analytics'

key_var_name = 'TEXT_ANALYTICS_SUBSCRIPTION_KEY'
if not key_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(key_var_name))
subscription_key = os.environ[key_var_name]

endpoint_var_name = 'TEXT_ANALYTICS_ENDPOINT'
if not endpoint_var_name in os.environ:
    raise Exception('Please set/export the environment variable: {}'.format(endpoint_var_name))
endpoint = os.environ[endpoint_var_name]

def authenticateClient():
    credentials = CognitiveServicesCredentials(subscription_key)
    text_analytics_client = TextAnalyticsClient(
        endpoint=endpoint, credentials=credentials)
    return text_analytics_client

sentence = input("Enter the string:")

def sentiment():

    client = authenticateClient()

    try:
        documents = [
            {"id": "1", "language": "en", "text": sentence}
        ]

        response = client.sentiment(documents=documents)
        for document in response.documents:
            print("Entered Text: ", document.text, ", Sentiment Score: ",
                  "{:.2f}".format(document.score))

    except Exception as err:
        print("Encountered exception. {}".format(err))
sentiment()

1 个答案:

答案 0 :(得分:0)

不建议您在此处共享您的订阅密钥,请尽快撤消此订阅密钥。对于您的问题,请尝试以下操作:

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

subscription_key = 'b2c4f0ee35c941078d9e6971c15c3472'
endpoint = 'https://westcentralus.api.cognitive.microsoft.com/'

def authenticateClient():
    credentials = CognitiveServicesCredentials(subscription_key)
    text_analytics_client = TextAnalyticsClient(
        endpoint=endpoint, credentials=credentials)
    return text_analytics_client

sentence = input("Enter the string:")

def sentiment():

    client = authenticateClient()

    try:
        documents = [
            {"id": "1", "language": "en", "text": sentence}
        ]



        response = client.sentiment(documents=documents)
        for document in response.documents:
            print("Entered Text: ",sentence ,", Sentiment Score: ",
                  "{:.2f}".format(document.score))


    except Exception as err:
        print("Encountered exception. {}".format(err))

sentiment()

结果:

enter image description here