Skip to content

Sentiment analysis

Sentiment analysis is a type of document analysis that determines how positive or negative the tone of the text is.

Sentiment analysis also performs knowledge linking: Knowledge Graph information and open data—Wikidata, DBpedia and GeoNames references—are returned for text items that express sentiment given they correspond to syncons of the expert.ai Knowledge Graph. In the case of actual places, geographic coordinates are also provided.

Full analysis includes sentiment analysis, but if you are not interested in the other analyses, you can use specific resources having paths like this:

analyze/context name/language code/sentiment

Boxed parts are placeholders, so for example:

https://nlapi.expert.ai/v2/analyze/standard/en/sentiment

is the URL of the standard context resource performing the sentiment analysis of an English text.
These resources must be requested with the POST method.

In the reference section of this manual you will find all the information you need to perform sentiment analysis using the API's RESTful interface, specifically:

Note

Even if you consume the API through a ready-to-use client that hides low-level requests and responses, knowing the output format helps you understand and navigate the results.

Here is an example of performing sentiment analysis on a short English text:

This example code uses expertai-nlapi, the open-source Python client corresponding to the nlapi-python GitHub project.

The client gets user credentials from two environment variables:

EAI_USERNAME
EAI_PASSWORD

Set those variables with your account credentials before running the sample program below.

The program prints the overall sentiment.

from expertai.nlapi.cloud.client import ExpertAiClient
client = ExpertAiClient()

text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half." 
language= 'en'

output = client.specific_resource_analysis(
    body={"document": {"text": text}}, 
    params={'language': language, 'resource': 'sentiment'
})

print("Output overall sentiment:")

print(output.sentiment.overall)

This example code uses @expertai/nlapi, the open-source NodeJS client corresponding to the nlapi-nodejs GitHub project.

The client gets user credentials from two environment variables:

EAI_USERNAME
EAI_PASSWORD

Set those variables with your account credentials before running the sample program below.

The program prints the overall sentiment.

import {NLClient} from "@expertai/nlapi";
import {Language} from "@expertai/nlapi";
import {Analysis} from "@expertai/nlapi";

var nlClient = new NLClient();

var text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half.";

nlClient.analyze(text, {
  language: Language.EN,
  context: "standard",
  analysis: Analysis.Sentiment
}).then((result) => {
    console.log("Overall sentiment:");
    console.log(result.data.sentiment.overall);
})

This example code uses nlapi-java-sdk, the open-source Java client corresponding to the nlapi-java GitHub project.

The client gets user credentials from two environment variables:

EAI_USERNAME
EAI_PASSWORD

Set those variables with your account credentials before running the sample program below.

The program prints the JSON response and the overall sentiment.

import ai.expert.nlapi.security.Authentication;
import ai.expert.nlapi.security.Authenticator;
import ai.expert.nlapi.security.BasicAuthenticator;
import ai.expert.nlapi.security.DefaultCredentialsProvider;
import ai.expert.nlapi.v2.API;
import ai.expert.nlapi.v2.cloud.Analyzer;
import ai.expert.nlapi.v2.cloud.AnalyzerConfig;
import ai.expert.nlapi.v2.message.AnalyzeResponse;
import ai.expert.nlapi.v2.model.AnalyzeDocument;

public class Main {

    public static Authentication createAuthentication() throws Exception {
        DefaultCredentialsProvider credentialsProvider = new DefaultCredentialsProvider();
        Authenticator authenticator = new BasicAuthenticator(credentialsProvider);
        return new Authentication(authenticator);
    }

    public static Analyzer createAnalyzer() throws Exception {
        return new Analyzer(AnalyzerConfig.builder()
                .withVersion(API.Versions.V2)
                .withContext("standard")
                .withLanguage(API.Languages.en)
                .withAuthentication(createAuthentication())
                .build());
    }

    public static void main(String[] args) {
        try {
            String text = "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half.";

            Analyzer analyzer = createAnalyzer();

            AnalyzeResponse sentiment = analyzer.sentiment(text);


            // Output JSON representation

            System.out.println("JSON representation:");
            sentiment.prettyPrint();


            // Overall sentiment.

            System.out.println("Overall sentiment:");
            AnalyzeDocument data = sentiment.getData();
            System.out.println(data.getSentiment().getOverall());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

The following curl command posts a document to the named entity recognition resource of the API's REST interface.
Run the command from a shell after replacing token with the actual authorization token.

curl -X POST https://nlapi.expert.ai/v2/analyze/standard/en/sentiment \
    -H 'Authorization: Bearer token' \
    -H 'Content-Type: application/json; charset=utf-8' \
    -d '{
  "document": {
    "text": "Michael Jordan was one of the best basketball players of all time. Scoring was Jordan'\''s stand-out skill, but he still holds a defensive NBA record, with eight steals in a half."
  }
}'

The server returns a JSON object.

The following curl command posts a document to the named entity recognition resource of the API's REST interface.
Open a command prompt in the folder where you installed curl and run the command after replacing token with the actual authorization token.

curl -X POST https://nlapi.expert.ai/v2/analyze/standard/en/sentiment  -H "Authorization: Bearer token" -H "Content-Type: application/json; charset=utf-8" -d "{\"document\": {\"text\": \"Michael Jordan was one of the best basketball players of all time. Scoring was Jordan's stand-out skill, but he still holds a defensive NBA record, with eight steals in a half.\"}}"

The server returns a JSON object