Quickstart: Sentiment analysis and opinion mining
Use this article to get started detecting sentiment and opinions in text. Follow these steps to try out examples code for mining text:
Reference documentation | Library source code | Package (NuGet) | Additional samples
Prerequisites
- Azure subscription - Create one for free
- The Visual Studio IDE
- Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
- You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
- You can use the free pricing tier (
F0) to try the service, and upgrade later to a paid tier for production.
- To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.
Setting up
Create a new .NET Core application
Using the Visual Studio IDE, create a new .NET Core console app. This will create a "Hello World" project with a single C# source file: program.cs.
Install the client library by right-clicking on the solution in the Solution Explorer and selecting Manage NuGet Packages. In the package manager that opens select Browse and search for Azure.AI.TextAnalytics. Select version 5.1.0, and then Install. You can also use the Package Manager Console.
Code example
Copy the following code into your program.cs file. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource.
Important
Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint in the resource's Keys and Endpoint page, under Resource Management.
Remember to remove the key from your code when you're done, and never post it publicly. For production, consider using a secure way of storing and accessing your credentials. For example, Azure key vault.
using Azure;
using System;
using Azure.AI.TextAnalytics;
using System.Collections.Generic;
namespace Example
{
class Program
{
private static readonly AzureKeyCredential credentials = new AzureKeyCredential("replace-with-your-key-here");
private static readonly Uri endpoint = new Uri("replace-with-your-endpoint-here");
// Example method for detecting sentiment from text.
static void SentimentAnalysisExample(TextAnalyticsClient client)
{
string inputText = "I had the best day of my life. I wish you were there with me.";
DocumentSentiment documentSentiment = client.AnalyzeSentiment(inputText);
Console.WriteLine($"Document sentiment: {documentSentiment.Sentiment}\n");
foreach (var sentence in documentSentiment.Sentences)
{
Console.WriteLine($"\tText: \"{sentence.Text}\"");
Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
Console.WriteLine($"\tPositive score: {sentence.ConfidenceScores.Positive:0.00}");
Console.WriteLine($"\tNegative score: {sentence.ConfidenceScores.Negative:0.00}");
Console.WriteLine($"\tNeutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
}
}
// Example method for detecting opinions text.
static void SentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
{
var documents = new List<string>
{
"The food and service were unacceptable, but the concierge were nice."
};
AnalyzeSentimentResultCollection reviews = client.AnalyzeSentimentBatch(documents, options: new AnalyzeSentimentOptions()
{
IncludeOpinionMining = true
});
foreach (AnalyzeSentimentResult review in reviews)
{
Console.WriteLine($"Document sentiment: {review.DocumentSentiment.Sentiment}\n");
Console.WriteLine($"\tPositive score: {review.DocumentSentiment.ConfidenceScores.Positive:0.00}");
Console.WriteLine($"\tNegative score: {review.DocumentSentiment.ConfidenceScores.Negative:0.00}");
Console.WriteLine($"\tNeutral score: {review.DocumentSentiment.ConfidenceScores.Neutral:0.00}\n");
foreach (SentenceSentiment sentence in review.DocumentSentiment.Sentences)
{
Console.WriteLine($"\tText: \"{sentence.Text}\"");
Console.WriteLine($"\tSentence sentiment: {sentence.Sentiment}");
Console.WriteLine($"\tSentence positive score: {sentence.ConfidenceScores.Positive:0.00}");
Console.WriteLine($"\tSentence negative score: {sentence.ConfidenceScores.Negative:0.00}");
Console.WriteLine($"\tSentence neutral score: {sentence.ConfidenceScores.Neutral:0.00}\n");
foreach (SentenceOpinion sentenceOpinion in sentence.Opinions)
{
Console.WriteLine($"\tTarget: {sentenceOpinion.Target.Text}, Value: {sentenceOpinion.Target.Sentiment}");
Console.WriteLine($"\tTarget positive score: {sentenceOpinion.Target.ConfidenceScores.Positive:0.00}");
Console.WriteLine($"\tTarget negative score: {sentenceOpinion.Target.ConfidenceScores.Negative:0.00}");
foreach (AssessmentSentiment assessment in sentenceOpinion.Assessments)
{
Console.WriteLine($"\t\tRelated Assessment: {assessment.Text}, Value: {assessment.Sentiment}");
Console.WriteLine($"\t\tRelated Assessment positive score: {assessment.ConfidenceScores.Positive:0.00}");
Console.WriteLine($"\t\tRelated Assessment negative score: {assessment.ConfidenceScores.Negative:0.00}");
}
}
}
Console.WriteLine($"\n");
}
}
static void Main(string[] args)
{
var client = new TextAnalyticsClient(endpoint, credentials);
SentimentAnalysisExample(client);
SentimentAnalysisWithOpinionMiningExample(client);
Console.Write("Press any key to exit.");
Console.ReadKey();
}
}
}
Output
Document sentiment: Positive
Text: "I had the best day of my life."
Sentence sentiment: Positive
Positive score: 1.00
Negative score: 0.00
Neutral score: 0.00
Text: "I wish you were there with me."
Sentence sentiment: Neutral
Positive score: 0.21
Negative score: 0.02
Neutral score: 0.77
Document sentiment: Positive
Positive score: 0.84
Negative score: 0.16
Neutral score: 0.00
Text: "The food and service were unacceptable, but the concierge were nice."
Sentence sentiment: Positive
Sentence positive score: 0.84
Sentence negative score: 0.16
Sentence neutral score: 0.00
Target: food, Value: Negative
Target positive score: 0.01
Target negative score: 0.99
Related Assessment: unacceptable, Value: Negative
Related Assessment positive score: 0.01
Related Assessment negative score: 0.99
Target: service, Value: Negative
Target positive score: 0.01
Target negative score: 0.99
Related Assessment: unacceptable, Value: Negative
Related Assessment positive score: 0.01
Related Assessment negative score: 0.99
Target: concierge, Value: Positive
Target positive score: 1.00
Target negative score: 0.00
Related Assessment: nice, Value: Positive
Related Assessment positive score: 1.00
Related Assessment negative score: 0.00
Press any key to exit.
Reference documentation | Library source code | Package | Samples
Prerequisites
- Azure subscription - Create one for free
- Java Development Kit (JDK) with version 8 or above
- Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
- You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
- You can use the free pricing tier (
F0) to try the service, and upgrade later to a paid tier for production.
- To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.
Setting up
Add the client library
Create a Maven project in your preferred IDE or development environment. Then add the following dependency to your project's pom.xml file. You can find the implementation syntax for other build tools online.
<dependencies>
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-ai-textanalytics</artifactId>
<version>5.1.9</version>
</dependency>
</dependencies>
Code example
Create a Java file named Example.java. Open the file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource.
Important
Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint in the resource's Keys and Endpoint page, under Resource Management.
Remember to remove the key from your code when you're done, and never post it publicly. For production, consider using a secure way of storing and accessing your credentials. For example, Azure key vault.
import com.azure.core.credential.AzureKeyCredential;
import com.azure.ai.textanalytics.models.*;
import com.azure.ai.textanalytics.TextAnalyticsClientBuilder;
import com.azure.ai.textanalytics.TextAnalyticsClient;
public class Example {
private static String KEY = "replace-with-your-key-here";
private static String ENDPOINT = "replace-with-your-endpoint-here";
public static void main(String[] args) {
TextAnalyticsClient client = authenticateClient(KEY, ENDPOINT);
sentimentAnalysisExample(client);
sentimentAnalysisWithOpinionMiningExample(client);
}
// Method to authenticate the client object with your key and endpoint.
static TextAnalyticsClient authenticateClient(String key, String endpoint) {
return new TextAnalyticsClientBuilder()
.credential(new AzureKeyCredential(key))
.endpoint(endpoint)
.buildClient();
}
// Example method for sentiment in text.
static void sentimentAnalysisExample(TextAnalyticsClient client)
{
// The text that need be analyzed.
String text = "I had the best day of my life. I wish you were there with me.";
DocumentSentiment documentSentiment = client.analyzeSentiment(text);
System.out.printf(
"Recognized document sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n",
documentSentiment.getSentiment(),
documentSentiment.getConfidenceScores().getPositive(),
documentSentiment.getConfidenceScores().getNeutral(),
documentSentiment.getConfidenceScores().getNegative());
for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) {
System.out.printf(
"Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n",
sentenceSentiment.getSentiment(),
sentenceSentiment.getConfidenceScores().getPositive(),
sentenceSentiment.getConfidenceScores().getNeutral(),
sentenceSentiment.getConfidenceScores().getNegative());
}
}
// Example method for detecting opinions in text.
static void sentimentAnalysisWithOpinionMiningExample(TextAnalyticsClient client)
{
// The document that needs be analyzed.
String document = "Bad atmosphere. Not close to plenty of restaurants, hotels, and transit! Staff are not friendly and helpful.";
System.out.printf("Document = %s%n", document);
AnalyzeSentimentOptions options = new AnalyzeSentimentOptions().setIncludeOpinionMining(true);
final DocumentSentiment documentSentiment = client.analyzeSentiment(document, "en", options);
SentimentConfidenceScores scores = documentSentiment.getConfidenceScores();
System.out.printf(
"Recognized document sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
documentSentiment.getSentiment(), scores.getPositive(), scores.getNeutral(), scores.getNegative());
documentSentiment.getSentences().forEach(sentenceSentiment -> {
SentimentConfidenceScores sentenceScores = sentenceSentiment.getConfidenceScores();
System.out.printf("\tSentence sentiment: %s, positive score: %f, neutral score: %f, negative score: %f.%n",
sentenceSentiment.getSentiment(), sentenceScores.getPositive(), sentenceScores.getNeutral(), sentenceScores.getNegative());
sentenceSentiment.getOpinions().forEach(opinion -> {
TargetSentiment targetSentiment = opinion.getTarget();
System.out.printf("\t\tTarget sentiment: %s, target text: %s%n", targetSentiment.getSentiment(),
targetSentiment.getText());
for (AssessmentSentiment assessmentSentiment : opinion.getAssessments()) {
System.out.printf("\t\t\t'%s' assessment sentiment because of \"%s\". Is the assessment negated: %s.%n",
assessmentSentiment.getSentiment(), assessmentSentiment.getText(), assessmentSentiment.isNegated());
}
});
});
}
}
Output
Recognized document sentiment: positive, positive score: 0.99, neutral score: 0.0, negative score: 0.0.
Recognized sentence sentiment: positive, positive score: 0.99, neutral score: 0.0, negative score: 0.0.
Recognized sentence sentiment: neutral, positive score: 0.25, neutral score: 0.72, negative score: 0.03.
Document = Bad atmosphere. Not close to plenty of restaurants, hotels, and transit! Staff are not friendly and helpful.
Recognized document sentiment: negative, positive score: 0.050000, neutral score: 0.030000, negative score: 0.920000.
Sentence sentiment: negative, positive score: 0.010000, neutral score: 0.000000, negative score: 0.990000.
Target sentiment: negative, target text: atmosphere
'negative' assessment sentiment because of "Bad". Is the assessment negated: false.
Sentence sentiment: negative, positive score: 0.140000, neutral score: 0.080000, negative score: 0.780000.
Sentence sentiment: negative, positive score: 0.010000, neutral score: 0.000000, negative score: 0.990000.
Target sentiment: negative, target text: Staff
'negative' assessment sentiment because of "friendly". Is the assessment negated: true.
'negative' assessment sentiment because of "helpful". Is the assessment negated: true.
Reference documentation | Library source code | Package (NPM) | Samples
Prerequisites
- Azure subscription - Create one for free
- The current version of Node.js.
- Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
- You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
- You can use the free pricing tier (
F0) to try the service, and upgrade later to a paid tier for production.
- To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.
Setting up
Create a new Node.js application
In a console window (such as cmd, PowerShell, or Bash), create a new directory for your app, and navigate to it.
mkdir myapp
cd myapp
Run the npm init command to create a node application with a package.json file.
npm init
Install the client library
Install the NPM packages:
npm install @azure/ai-text-analytics@5.1.0
Code example
Open the file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource.
Important
Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint in the resource's Keys and Endpoint page, under Resource Management.
Remember to remove the key from your code when you're done, and never post it publicly. For production, consider using a secure way of storing and accessing your credentials. For example, Azure key vault.
"use strict";
const { TextAnalyticsClient, AzureKeyCredential } = require("@azure/ai-text-analytics");
const key = '<paste-your-key-here>';
const endpoint = '<paste-your-endpoint-here>';
// Authenticate the client with your key and endpoint.
const textAnalyticsClient = new TextAnalyticsClient(endpoint, new AzureKeyCredential(key));
// Example method for detecting sentiment in text.
async function sentimentAnalysis(client){
const sentimentInput = [
"I had the best day of my life. I wish you were there with me."
];
const sentimentResult = await client.analyzeSentiment(sentimentInput);
sentimentResult.forEach(document => {
console.log(`ID: ${document.id}`);
console.log(`\tDocument Sentiment: ${document.sentiment}`);
console.log(`\tDocument Scores:`);
console.log(`\t\tPositive: ${document.confidenceScores.positive.toFixed(2)} \tNegative: ${document.confidenceScores.negative.toFixed(2)} \tNeutral: ${document.confidenceScores.neutral.toFixed(2)}`);
console.log(`\tSentences Sentiment(${document.sentences.length}):`);
document.sentences.forEach(sentence => {
console.log(`\t\tSentence sentiment: ${sentence.sentiment}`)
console.log(`\t\tSentences Scores:`);
console.log(`\t\tPositive: ${sentence.confidenceScores.positive.toFixed(2)} \tNegative: ${sentence.confidenceScores.negative.toFixed(2)} \tNeutral: ${sentence.confidenceScores.neutral.toFixed(2)}`);
});
});
}
sentimentAnalysis(textAnalyticsClient)
// Example method for detecting opinions in text.
async function sentimentAnalysisWithOpinionMining(client){
const sentimentInput = [
{
text: "The food and service were unacceptable, but the concierge were nice",
id: "0",
language: "en"
}
];
const results = await client.analyzeSentiment(sentimentInput, { includeOpinionMining: true });
for (let i = 0; i < results.length; i++) {
const result = results[i];
console.log(`- Document ${result.id}`);
if (!result.error) {
console.log(`\tDocument text: ${sentimentInput[i].text}`);
console.log(`\tOverall Sentiment: ${result.sentiment}`);
console.log("\tSentiment confidence scores:", result.confidenceScores);
console.log("\tSentences");
for (const { sentiment, confidenceScores, opinions } of result.sentences) {
console.log(`\t- Sentence sentiment: ${sentiment}`);
console.log("\t Confidence scores:", confidenceScores);
console.log("\t Mined opinions");
for (const { target, assessments } of opinions) {
console.log(`\t\t- Target text: ${target.text}`);
console.log(`\t\t Target sentiment: ${target.sentiment}`);
console.log("\t\t Target confidence scores:", target.confidenceScores);
console.log("\t\t Target assessments");
for (const { text, sentiment } of assessments) {
console.log(`\t\t\t- Text: ${text}`);
console.log(`\t\t\t Sentiment: ${sentiment}`);
}
}
}
} else {
console.error(`\tError: ${result.error}`);
}
}
}
sentimentAnalysisWithOpinionMining(textAnalyticsClient);
Output
ID: 0
Document Sentiment: positive
Document Scores:
Positive: 1.00 Negative: 0.00 Neutral: 0.00
Sentences Sentiment(2):
Sentence sentiment: positive
Sentences Scores:
Positive: 1.00 Negative: 0.00 Neutral: 0.00
Sentence sentiment: neutral
Sentences Scores:
Positive: 0.21 Negative: 0.02 Neutral: 0.77
- Document 0
Document text: The food and service were unacceptable, but the concierge were nice
Overall Sentiment: positive
Sentiment confidence scores: { positive: 0.84, neutral: 0, negative: 0.16 }
Sentences
- Sentence sentiment: positive
Confidence scores: { positive: 0.84, neutral: 0, negative: 0.16 }
Mined opinions
- Target text: food
Target sentiment: negative
Target confidence scores: { positive: 0.01, negative: 0.99 }
Target assessments
- Text: unacceptable
Sentiment: negative
- Target text: service
Target sentiment: negative
Target confidence scores: { positive: 0.01, negative: 0.99 }
Target assessments
- Text: unacceptable
Sentiment: negative
- Target text: concierge
Target sentiment: positive
Target confidence scores: { positive: 1, negative: 0 }
Target assessments
- Text: nice
Sentiment: positive
Reference documentation | Library source code | Package (PiPy) | Samples
Prerequisites
- Azure subscription - Create one for free
- Python 3.x
- Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
- You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
- You can use the free pricing tier (
F0) to try the service, and upgrade later to a paid tier for production.
- To use the Analyze feature, you will need a Language resource with the standard (S) pricing tier.
Setting up
Install the client library
After installing Python, you can install the client library with:
pip install azure-ai-textanalytics==5.1.0
Code example
Create a new Python file and copy the below code. Remember to replace the key variable with the key for your resource, and replace the endpoint variable with the endpoint for your resource.
Important
Go to the Azure portal. If the Language resource you created in the Prerequisites section deployed successfully, click the Go to Resource button under Next Steps. You can find your key and endpoint in the resource's Keys and Endpoint page, under Resource Management.
Remember to remove the key from your code when you're done, and never post it publicly. For production, consider using a secure way of storing and accessing your credentials. For example, Azure key vault.
key = "paste-your-key-here"
endpoint = "paste-your-endpoint-here"
from azure.ai.textanalytics import TextAnalyticsClient
from azure.core.credentials import AzureKeyCredential
# Authenticate the client using your key and endpoint
def authenticate_client():
ta_credential = AzureKeyCredential(key)
text_analytics_client = TextAnalyticsClient(
endpoint=endpoint,
credential=ta_credential)
return text_analytics_client
client = authenticate_client()
# Example function for detecting sentiment in text
def sentiment_analysis_example(client):
documents = ["I had the best day of my life. I wish you were there with me."]
response = client.analyze_sentiment(documents=documents)[0]
print("Document Sentiment: {}".format(response.sentiment))
print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
response.confidence_scores.positive,
response.confidence_scores.neutral,
response.confidence_scores.negative,
))
for idx, sentence in enumerate(response.sentences):
print("Sentence: {}".format(sentence.text))
print("Sentence {} sentiment: {}".format(idx+1, sentence.sentiment))
print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
sentence.confidence_scores.positive,
sentence.confidence_scores.neutral,
sentence.confidence_scores.negative,
))
sentiment_analysis_example(client)
# Example method for detecting opinions in text
def sentiment_analysis_with_opinion_mining_example(client):
documents = [
"The food and service were unacceptable, but the concierge were nice"
]
result = client.analyze_sentiment(documents, show_opinion_mining=True)
doc_result = [doc for doc in result if not doc.is_error]
positive_reviews = [doc for doc in doc_result if doc.sentiment == "positive"]
negative_reviews = [doc for doc in doc_result if doc.sentiment == "negative"]
positive_mined_opinions = []
mixed_mined_opinions = []
negative_mined_opinions = []
for document in doc_result:
print("Document Sentiment: {}".format(document.sentiment))
print("Overall scores: positive={0:.2f}; neutral={1:.2f}; negative={2:.2f} \n".format(
document.confidence_scores.positive,
document.confidence_scores.neutral,
document.confidence_scores.negative,
))
for sentence in document.sentences:
print("Sentence: {}".format(sentence.text))
print("Sentence sentiment: {}".format(sentence.sentiment))
print("Sentence score:\nPositive={0:.2f}\nNeutral={1:.2f}\nNegative={2:.2f}\n".format(
sentence.confidence_scores.positive,
sentence.confidence_scores.neutral,
sentence.confidence_scores.negative,
))
for mined_opinion in sentence.mined_opinions:
target = mined_opinion.target
print("......'{}' target '{}'".format(target.sentiment, target.text))
print("......Target score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
target.confidence_scores.positive,
target.confidence_scores.negative,
))
for assessment in mined_opinion.assessments:
print("......'{}' assessment '{}'".format(assessment.sentiment, assessment.text))
print("......Assessment score:\n......Positive={0:.2f}\n......Negative={1:.2f}\n".format(
assessment.confidence_scores.positive,
assessment.confidence_scores.negative,
))
print("\n")
print("\n")
sentiment_analysis_with_opinion_mining_example(client)
Output
Document Sentiment: positive
Overall scores: positive=1.00; neutral=0.00; negative=0.00
Sentence: I had the best day of my life.
Sentence 1 sentiment: positive
Sentence score:
Positive=1.00
Neutral=0.00
Negative=0.00
Sentence: I wish you were there with me.
Sentence 2 sentiment: neutral
Sentence score:
Positive=0.21
Neutral=0.77
Negative=0.02
Document Sentiment: positive
Overall scores: positive=0.84; neutral=0.00; negative=0.16
Sentence: The food and service were unacceptable, but the concierge were nice
Sentence sentiment: positive
Sentence score:
Positive=0.84
Neutral=0.00
Negative=0.16
......'negative' target 'food'
......Target score:
......Positive=0.01
......Negative=0.99
......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.01
......Negative=0.99
......'negative' target 'service'
......Target score:
......Positive=0.01
......Negative=0.99
......'negative' assessment 'unacceptable'
......Assessment score:
......Positive=0.01
......Negative=0.99
......'positive' target 'concierge'
......Target score:
......Positive=1.00
......Negative=0.00
......'positive' assessment 'nice'
......Assessment score:
......Positive=1.00
......Negative=0.00
Prerequisites
- The current version of cURL.
- Once you have your Azure subscription, create a Language resource in the Azure portal to get your key and endpoint. After it deploys, click Go to resource.
- You will need the key and endpoint from the resource you create to connect your application to the API. You'll paste your key and endpoint into the code below later in the quickstart.
- You can use the free pricing tier (
F0) to try the service, and upgrade later to a paid tier for production.
Note
- The following BASH examples use the
\line continuation character. If your console or terminal uses a different line continuation character, use that character. - You can find language specific samples on GitHub.
- Go to the Azure portal and find the key and endpoint for the Language resource you created in the prerequisites. They will be located on the resource's key and endpoint page, under resource management. Then replace the strings in the code below with your key and endpoint. To call the API, you need the following information:
| parameter | Description |
|---|---|
-X POST <endpoint> |
Specifies your endpoint for accessing the API. |
-H Content-Type: application/json |
The content type for sending JSON data. |
-H "Ocp-Apim-Subscription-Key:<key> |
Specifies the key for accessing the API. |
-d <documents> |
The JSON containing the documents you want to send. |
The following cURL commands are executed from a BASH shell. Edit these commands with your own resource name, resource key, and JSON values.
Sentiment analysis and opinion mining
- Copy the command into a text editor.
- Make the following changes in the command where needed:
- Replace the value
<your-text-analytics-key-here>with your key. - Replace the first part of the request URL
<your-text-analytics-endpoint-here>with the your own endpoint URL.
- Replace the value
- Open a command prompt window.
- Paste the command from the text editor into the command prompt window, and then run the command.
Note
The below examples include a request for the Opinion Mining feature of Sentiment Analysis using the opinionMining=true parameter, which provides granular information about assessments (adjectives) related to targets (nouns) in the text.
curl -X POST https://<your-text-analytics-endpoint-here>/text/analytics/v3.2-preview.1/sentiment?opinionMining=true \
-H "Content-Type: application/json" \
-H "Ocp-Apim-Subscription-Key: <your-text-analytics-key-here>" \
-d '{ documents: [{ id: "1", text: "The customer service here is really good."}]}'
JSON response
{
"documents":[
{
"id":"1",
"sentiment":"positive",
"confidenceScores":{
"positive":1.0,
"neutral":0.0,
"negative":0.0
},
"sentences":[
{
"sentiment":"positive",
"confidenceScores":{
"positive":1.0,
"neutral":0.0,
"negative":0.0
},
"offset":0,
"length":41,
"text":"The customer service here is really good.",
"targets":[
{
"sentiment":"positive",
"confidenceScores":{
"positive":1.0,
"negative":0.0
},
"offset":4,
"length":16,
"text":"customer service",
"relations":[
{
"relationType":"assessment",
"ref":"#/documents/0/sentences/0/assessments/0"
}
]
}
],
"assessments":[
{
"sentiment":"positive",
"confidenceScores":{
"positive":1.0,
"negative":0.0
},
"offset":36,
"length":4,
"text":"good",
"isNegated":false
}
]
}
],
"warnings":[
]
}
],
"errors":[
],
"modelVersion":"2020-04-01"
}
Clean up resources
If you want to clean up and remove a Cognitive Services subscription, you can delete the resource or resource group. Deleting the resource group also deletes any other resources associated with it.
Next steps
Tilbakemeldinger
Send inn og vis tilbakemelding for