항목 감정 분석

항목 감정 분석은 항목 분석과 감정 분석을 결합하며, 텍스트 내에서 항목에 대해 표현되는 감정(긍정적 또는 부정적)을 판단하려고 시도합니다. 항목 감정은 score 및 magnitude의 숫자 값으로 표현되며, 항목의 각 멘션에 대해 결정됩니다. 해당 점수가 집계되어 항목의 전체 감정 score 및 magnitude가 결정됩니다. 분석에 포함된 scoremagnitude 감정 값을 해석하는 방법에 대한 자세한 내용은 감정 분석값 해석을 참조하세요.

다음 예에서는 analyzeEntitySentiment 메소드를 쿼리하는 방법을 보여줍니다.

항목 감정 분석

다음은 문자열로 제공된 항목 감정을 분석하는 예입니다.

프로토콜

문서의 항목 감정을 분석하려면 documents:analyzeEntitySentiment REST 메소드에 POST 요청을 하고 다음 예와 같이 적절한 요청 본문을 제공해야 합니다.

이 예에서는 gcloud auth application-default print-access-token 명령어를 사용하여 Google Cloud Platform Cloud SDK를 사용하는 프로젝트용으로 설정된 서비스 계정에 대한 액세스 토큰을 얻습니다. 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,
		},
	})
}

자바

// 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}");
    }
}

자바

// 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
도움이 필요하시나요? 지원 페이지를 방문하세요.