我想使用Microsoft Azure的情绪分析API。我使用它们的示例代码(https://docs.microsoft.com/en-us/azure/cognitive-services/text-analytics/quickstarts/python)如下。
# -*- coding: utf-8 -*
import requests
# pprint is used to format the JSON response
from pprint import pprint
import os
subscription_key = "*********"
endpoint = "https://westcentralus.api.cognitive.microsoft.com/text/analytics"
sentiment_url = endpoint + "/text/analytics/v2.1/sentiment"
documents = {"documents": [
{"id": "1", "language": "en",
"text": "I had a wonderful experience! The rooms were wonderful and the staff was helpful."},
{"id": "2", "language": "en",
"text": "I had a terrible time at the hotel. The staff was rude and the food was awful."},
{"id": "3", "language": "es",
"text": "Los caminos que llevan hasta Monte Rainier son espectaculares y hermosos."},
{"id": "4", "language": "es",
"text": "La carretera estaba atascada. Había mucho tráfico el día de ayer."}
]}
headers = {"Ocp-Apim-Subscription-Key": subscription_key}
response = requests.post(sentiment_url, headers=headers, json=documents)
sentiments = response.json()
pprint(sentiments)
但是它只返回{'error': {'code': '404', 'message': 'Resource not found'}}
是什么问题?
[我在分析的这一方面还没有做很多事情,所以我可能完全不满意,但是在我看来,您的“文本/分析”增加了一倍。
endpoint = "https://westcentralus.api.cognitive.microsoft.com/text/analytics"
sentiment_url = endpoint + "/text/analytics/v2.1/sentiment"
将给出最终结果https://westcentralus.api.cognitive.microsoft.com/text/analytics/text/analytics/v2.1/sentiment
它可能应该是:
https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.1/sentiment
您可以尝试以下代码
验证客户端
def authenticateClient():
credentials = CognitiveServicesCredentials(subscription_key)
text_analytics_client = TextAnalyticsClient(
endpoint=endpoint, credentials=credentials)
return text_analytics_client
情感分析
def sentiment():
client = authenticateClient()
try:
documents = [
{"id": "1", "language": "en", "text": "I had the best day of my life."},
{"id": "2", "language": "en",
"text": "This was a waste of my time. The speaker put me to sleep."},
{"id": "3", "language": "es", "text": "No tengo dinero ni nada que dar..."},
{"id": "4", "language": "it",
"text": "L'hotel veneziano era meraviglioso. È un bellissimo pezzo di architettura."}
]
response = client.sentiment(documents=documents)
for document in response.documents:
print("Document Id: ", document.id, ", Sentiment Score: ",
"{:.2f}".format(document.score))
except Exception as err:
print("Encountered exception. {}".format(err))
sentiment()
有关更多详细信息,请参考this official docs