Анализ настроений с использованием лазурной ошибки «Ресурс не найден»

Я создал программу на Python, которая принимает строку в качестве входных данных и выполняет для нее анализ настроений.

Я создал переменную среды, как указано в ДОКУМЕНТАЦИИ, а также перезапустил cmd и Visual Studio, но все равно получаю следующую ошибку:

Обнаружено исключение. Операция вернула недопустимый код состояния «Ресурс не найден».

Программа на питоне выглядит следующим образом:

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()

person EvilReboot    schedule 05.12.2019    source источник


Ответы (1)


Не рекомендуется делиться здесь своим ключом подписки, пожалуйста, отзовите этот ключ подписки как можно скорее. В случае вашей проблемы попробуйте следующее:

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()

Результат :

введите здесь описание изображения

person Stanley Gong    schedule 09.12.2019
comment
API был предназначен только для демонстрационных целей, он доступен бесплатно на Azure и действителен только в течение 7 дней. Спасибо за решения. мне нравится Бро - person EvilReboot; 10.12.2019