エンティティ感情分析

エンティティ感情分析とは、エンティティ分析と感情分析の両方を組み合わせたものであり、テキスト内でエンティティについて表現された感情(ポジティブかネガティブか)の特定を試みることです。エンティティ感情を表すには、数値のスコアと強度の値が使用され、そのエンティティについて言及されるたびに感情が特定されます。このスコアを集計して、そのエンティティの全体的な感情スコアと強度が計算されます。分析に含まれる感情の値 score および magnitude を解釈する方法については、感情分析の値の解釈をご覧ください。

以降の例で、analyzeEntitySentiment メソッドに対してクエリを実行する方法を説明します。

エンティティ感情分析

文字列として提供されたエンティティの感情を分析する例を次に示します。

プロトコル

ドキュメント内のエンティティ感情を分析するには、documents:analyzeEntitySentiment REST メソッドに対して POST リクエストを行います。リクエストには、次の例に示す適切なリクエスト本文を指定します。

この例では、Google Cloud Platform の Cloud SDK を使用してプロジェクト用にセットアップされたサービス アカウントのアクセス トークンを取得するために、gcloud auth application-default print-access-token コマンドを使用しています。Cloud SDK をインストールし、サービス アカウントを使用してプロジェクトをセットアップする手順については、クイックスタートをご覧ください。

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'document':{
    'type':'PLAIN_TEXT',
    'content':'I love R&B music. Marvin Gaye is the best.
               \'What\'s Going On\' is one of my favorite songs.
               It was so sad when Marvin Gaye died.'
  },
  'encodingType':'UTF8'
}" "https://language.googleapis.com/v1/documents:analyzeEntitySentiment"

gcloud コマンド

詳しくは、analyze-entity-sentiment コマンドをご覧ください。

エンティティ感情分析を実行するには、gcloud コマンドライン ツールを使用し、--content フラグを使用して、分析するコンテンツを指定します。

gcloud ml language analyze-entity-sentiment \
  --content="I love R&B music. Marvin Gaye is the best. 'What's Going On' is one of my favorite songs. It was so sad when Marvin Gaye died."

C#

private static void AnalyzeEntitySentimentFromText(string text)
{
    var client = LanguageServiceClient.Create();
    var response = client.AnalyzeEntitySentiment(new Document()
    {
        Content = text,
        Type = Document.Types.Type.PlainText
    });
    WriteEntitySentiment(response.Entities);
}

private static void WriteEntitySentiment(IEnumerable<Entity> entities)
{
    Console.WriteLine("Entity Sentiment:");
    foreach (var entity in entities)
    {
        Console.WriteLine($"\t{entity.Name} "
            + $"({(int)(entity.Salience * 100)}%)");
        Console.WriteLine($"\t\tScore: {entity.Sentiment.Score}");
        Console.WriteLine($"\t\tMagnitude { entity.Sentiment.Magnitude}");
    }
}

Go

func analyzeEntitySentiment(ctx context.Context, client *language.Client, text string) (*languagepb.AnalyzeEntitySentimentResponse, error) {
	return client.AnalyzeEntitySentiment(ctx, &languagepb.AnalyzeEntitySentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
}

Java

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc = Document.newBuilder()
      .setContent(text).setType(Type.PLAIN_TEXT).build();
  AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
      .setDocument(doc)
      .setEncodingType(EncodingType.UTF16).build();
  // detect entity sentiments in the given string
  AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
  // Print the response
  for (Entity entity : response.getEntitiesList()) {
    System.out.printf("Entity: %s\n", entity.getName());
    System.out.printf("Salience: %.3f\n", entity.getSalience());
    System.out.printf("Sentiment : %s\n", entity.getSentiment());
    for (EntityMention mention : entity.getMentionsList()) {
      System.out.printf("Begin offset: %d\n", mention.getText().getBeginOffset());
      System.out.printf("Content: %s\n", mention.getText().getContent());
      System.out.printf("Magnitude: %.3f\n", mention.getSentiment().getMagnitude());
      System.out.printf("Sentiment score : %.3f\n", mention.getSentiment().getScore());
      System.out.printf("Type: %s\n\n", mention.getType());
    }
  }
}

Node.js

// Imports the Google Cloud client library
const language = require('@google-cloud/language');

// Creates a client
const client = new language.LanguageServiceClient();

/**
 * TODO(developer): Uncomment the following line to run this code.
 */
// const text = 'Your text to analyze, e.g. Hello, world!';

// Prepares a document, representing the provided text
const document = {
  content: text,
  type: 'PLAIN_TEXT',
};

// Detects sentiment of entities in the document
const [result] = await client.analyzeEntitySentiment({document});
const entities = result.entities;

console.log(`Entities and sentiments:`);
entities.forEach(entity => {
  console.log(`  Name: ${entity.name}`);
  console.log(`  Type: ${entity.type}`);
  console.log(`  Score: ${entity.sentiment.score}`);
  console.log(`  Magnitude: ${entity.sentiment.magnitude}`);
});

Python

import six
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

text = 'President Kennedy spoke at the White House.'

client = language.LanguageServiceClient()

if isinstance(text, six.binary_type):
    text = text.decode('utf-8')

document = types.Document(
    content=text.encode('utf-8'),
    type=enums.Document.Type.PLAIN_TEXT)

# Detect and send native Python encoding to receive correct word offsets.
encoding = enums.EncodingType.UTF32
if sys.maxunicode == 65535:
    encoding = enums.EncodingType.UTF16

result = client.analyze_entity_sentiment(document, encoding)

for entity in result.entities:
    print('Mentions: ')
    print(u'Name: "{}"'.format(entity.name))
    for mention in entity.mentions:
        print(u'  Begin Offset : {}'.format(mention.text.begin_offset))
        print(u'  Content : {}'.format(mention.text.content))
        print(u'  Magnitude : {}'.format(mention.sentiment.magnitude))
        print(u'  Sentiment : {}'.format(mention.sentiment.score))
        print(u'  Type : {}'.format(mention.type))
    print(u'Salience: {}'.format(entity.salience))
    print(u'Sentiment: {}\n'.format(entity.sentiment))

PHP

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\V1beta2\Document;
use Google\Cloud\Language\V1beta2\Document\Type;
use Google\Cloud\Language\V1beta2\LanguageServiceClient;

/**
 * Find the entities in text.
 * ```
 * analyze_entity_sentiment('Do you know the way to San Jose?');
 * ```
 *
 * @param string $text The text to analyze.
 * @param string $projectId (optional) Your Google Cloud Project ID
 *
 */

function analyze_entity_sentiment($text, $projectId = null)
{
    $languageServiceClient = new LanguageServiceClient(['projectId' => $projectId]);
    try {
        $entity_types = [
            0 => 'UNKNOWN',
            1 => 'PERSON',
            2 => 'LOCATION',
            3 => 'ORGANIZATION',
            4 => 'EVENT',
            5 => 'WORK_OF_ART',
            6 => 'CONSUMER_GOOD',
            7 => 'OTHER',
        ];
        // Create a new Document
        $document = new Document();
        // Add text as content and set document type to PLAIN_TEXT
        $document->setContent($text)->setType(Type::PLAIN_TEXT);
        // Call the analyzeEntitySentiment function
        $response = $languageServiceClient->analyzeEntitySentiment($document);
        $entities = $response->getEntities();
        // Print out information about each entity
        foreach ($entities as $entity) {
            printf('Entity Name: %s' . PHP_EOL, $entity->getName());
            printf('Entity Type: %s' . PHP_EOL, $entity_types[$entity->getType()]);
            printf('Entity Salience: %s' . PHP_EOL, $entity->getSalience());
            $sentiment = $entity->getSentiment();
            if ($sentiment) {
                printf('Entity Magnitude: %s' . PHP_EOL, $sentiment->getMagnitude());
                printf('Entity Score: %s' . PHP_EOL, $sentiment->getScore());
            }
            print(PHP_EOL);
        }
    } finally {
        $languageServiceClient->close();
    }
}

Google Cloud Storage 内のエンティティの感情分析

Google Cloud Storage 上のテキスト ファイルに保存されたエンティティの感情を分析する例を次に示します。

プロトコル

Google Cloud Storage に保存されたドキュメントのエンティティ感情を分析するには、documents:analyzeEntitySentiment REST メソッドに対して POST リクエストを行います。リクエストには、次の例に示す適切なリクエスト本文とドキュメントへのパスを指定します。

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'document':{
    'type':'PLAIN_TEXT',
    'gcsContentUri':'gs://<bucket-name>/<object-name>'
  }
}" "https://language.googleapis.com/v1/documents:analyzeEntitySentiment"

gcloud コマンド

詳しくは、analyze-entity-sentiment コマンドをご覧ください。

エンティティ感情分析を実行するには、gcloud コマンドライン ツールを使用し、--content フラグを使用して、分析するコンテンツを指定します。

gcloud ml language analyze-entity-sentiment \
  --content-file=gs://<bucket-name>/<object-name>

C#

private static void AnalyzeEntitySentimentFromFile(string gcsUri)
{
    var client = LanguageServiceClient.Create();
    var response = client.AnalyzeEntitySentiment(new Document()
    {
        GcsContentUri = gcsUri,
        Type = Document.Types.Type.PlainText
    });
    WriteEntitySentiment(response.Entities);
}
private static void WriteEntitySentiment(IEnumerable<Entity> entities)
{
    Console.WriteLine("Entity Sentiment:");
    foreach (var entity in entities)
    {
        Console.WriteLine($"\t{entity.Name} "
            + $"({(int)(entity.Salience * 100)}%)");
        Console.WriteLine($"\t\tScore: {entity.Sentiment.Score}");
        Console.WriteLine($"\t\tMagnitude { entity.Sentiment.Magnitude}");
    }
}

Java

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc = Document.newBuilder()
      .setGcsContentUri(gcsUri)
      .setType(Type.PLAIN_TEXT)
      .build();
  AnalyzeEntitySentimentRequest request = AnalyzeEntitySentimentRequest.newBuilder()
      .setDocument(doc)
      .setEncodingType(EncodingType.UTF16)
      .build();
  // Detect entity sentiments in the given file
  AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
  // Print the response
  for (Entity entity : response.getEntitiesList()) {
    System.out.printf("Entity: %s\n", entity.getName());
    System.out.printf("Salience: %.3f\n", entity.getSalience());
    System.out.printf("Sentiment : %s\n", entity.getSentiment());
    for (EntityMention mention : entity.getMentionsList()) {
      System.out.printf("Begin offset: %d\n", mention.getText().getBeginOffset());
      System.out.printf("Content: %s\n", mention.getText().getContent());
      System.out.printf("Magnitude: %.3f\n", mention.getSentiment().getMagnitude());
      System.out.printf("Sentiment score : %.3f\n", mention.getSentiment().getScore());
      System.out.printf("Type: %s\n\n", mention.getType());
    }
  }
}

Node.js

// Imports the Google Cloud client library
const language = require('@google-cloud/language');

// Creates a client
const client = new language.LanguageServiceClient();

/**
 * TODO(developer): Uncomment the following lines to run this code
 */
// const bucketName = 'Your bucket name, e.g. my-bucket';
// const fileName = 'Your file name, e.g. my-file.txt';

// Prepares a document, representing a text file in Cloud Storage
const document = {
  gcsContentUri: `gs://${bucketName}/${fileName}`,
  type: 'PLAIN_TEXT',
};

// Detects sentiment of entities in the document
const [result] = await client.analyzeEntitySentiment({document});
const entities = result.entities;

console.log(`Entities and sentiments:`);
entities.forEach(entity => {
  console.log(`  Name: ${entity.name}`);
  console.log(`  Type: ${entity.type}`);
  console.log(`  Score: ${entity.sentiment.score}`);
  console.log(`  Magnitude: ${entity.sentiment.magnitude}`);
});

Python

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

gcs_uri = 'gs://cloud-samples-data/language/president.txt'

client = language.LanguageServiceClient()

document = types.Document(
    gcs_content_uri=gcs_uri,
    type=enums.Document.Type.PLAIN_TEXT)

# Detect and send native Python encoding to receive correct word offsets.
encoding = enums.EncodingType.UTF32
if sys.maxunicode == 65535:
    encoding = enums.EncodingType.UTF16

result = client.analyze_entity_sentiment(document, encoding)

for entity in result.entities:
    print(u'Name: "{}"'.format(entity.name))
    for mention in entity.mentions:
        print(u'  Begin Offset : {}'.format(mention.text.begin_offset))
        print(u'  Content : {}'.format(mention.text.content))
        print(u'  Magnitude : {}'.format(mention.sentiment.magnitude))
        print(u'  Sentiment : {}'.format(mention.sentiment.score))
        print(u'  Type : {}'.format(mention.type))
    print(u'Salience: {}'.format(entity.salience))
    print(u'Sentiment: {}\n'.format(entity.sentiment))

PHP

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\V1beta2\Document;
use Google\Cloud\Language\V1beta2\Document\Type;
use Google\Cloud\Language\V1beta2\LanguageServiceClient;

/**
 * Find the entities in text.
 * ```
 * analyze_entity_sentiment_from_file('gs://storage-bucket/file-name');
 * ```
 *
 * @param string $gcsUri Your Cloud Storage bucket URI
 * @param string $projectId (optional) Your Google Cloud Project ID
 *
 */

function analyze_entity_sentiment_from_file($gcsUri, $projectId = null)
{
    // Create the Natural Language client
    $languageServiceClient = new LanguageServiceClient(['projectId' => $projectId]);
    try {
        $entity_types = [
            0 => 'UNKNOWN',
            1 => 'PERSON',
            2 => 'LOCATION',
            3 => 'ORGANIZATION',
            4 => 'EVENT',
            5 => 'WORK_OF_ART',
            6 => 'CONSUMER_GOOD',
            7 => 'OTHER',
        ];
        // Create a new Document
        $document = new Document();
        // Pass GCS URI and set document type to PLAIN_TEXT
        $document->setGcsContentUri($gcsUri)->setType(Type::PLAIN_TEXT);
        // Call the analyzeEntitySentiment function
        $response = $languageServiceClient->analyzeEntitySentiment($document);
        $entities = $response->getEntities();
        // Print out information about each entity
        foreach ($entities as $entity) {
            printf('Entity Name: %s' . PHP_EOL, $entity->getName());
            printf('Entity Type: %s' . PHP_EOL, $entity_types[$entity->getType()]);
            printf('Entity Salience: %s' . PHP_EOL, $entity->getSalience());
            $sentiment = $entity->getSentiment();
            if ($sentiment) {
                printf('Entity Magnitude: %s' . PHP_EOL, $sentiment->getMagnitude());
                printf('Entity Score: %s' . PHP_EOL, $sentiment->getScore());
            }
            print(PHP_EOL);
        }
    } finally {
        $languageServiceClient->close();
    }
}

このページは役立ちましたか?評価をお願いいたします。

フィードバックを送信...

Cloud Natural Language API
ご不明な点がありましたら、Google のサポートページをご覧ください。