감정 분석

감정 분석은 주어진 텍스트를 조사하고 텍스트 내의 주도적인 감정적 의견을 식별하여 작성자의 태도가 긍정적인지, 부정적인지 또는 중립적인지를 판단합니다. 감정 분석은 analyzeSentiment 메서드를 통해 수행됩니다. Natural Language API에서 지원되는 언어에 대한 자세한 내용은 언어 지원을 참조하세요. 분석에 포함된 scoremagnitude 감정 값을 해석하는 방법에 대한 자세한 내용은 감정 분석값 해석을 참조하세요.

이 섹션에서는 문서에서 감정을 감지하는 몇 가지 방법을 보여줍니다. 문서마다 별도의 요청을 제출해야 합니다.

문자열 내 감정 분석

다음은 Natural Language API로 직접 전송된 텍스트 문자열에 대한 감정 분석을 수행하는 예입니다.

프로토콜

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

이 예시에서는 gcloud auth application-default print-access-token 명령어를 사용하여 Google Cloud Platform gcloud CLI를 사용하는 프로젝트용으로 설정된 서비스 계정에 대한 액세스 토큰을 얻습니다. gcloud CLI를 설치하고 서비스 계정을 통해 프로젝트를 설정하는 방법에 대한 안내는 빠른 시작을 참조하세요.

curl -X POST \
     -H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
  'encodingType': 'UTF8',
  'document': {
    'type': 'PLAIN_TEXT',
    'content': 'Enjoy your vacation!'
  }
}" "https://language.googleapis.com/v2/documents:analyzeSentiment"

document.language_code를 지정하지 않으면 언어가 자동으로 감지됩니다. Natural Language API에서 지원되는 언어에 대한 자세한 내용은 언어 지원을 참조하세요. 요청 본문 구성에 대한 자세한 내용은 Document 참조 문서를 확인하세요.

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score가 0보다 크면 긍정적인 감정을 나타내며 0보다 작으면 부정적인 감정을 나타냅니다.

gcloud

자세한 내용은 analyze-sentiment 명령어를 참조하세요.

감정 분석을 수행하려면 gcloud CLI와 --content 플래그를 사용하여 분석할 콘텐츠를 식별합니다.

gcloud ml language analyze-sentiment --content="Enjoy your vacation!"

요청이 성공하면 서버는 JSON 형식의 응답을 반환합니다.

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score가 0보다 크면 긍정적인 감정을 나타내며 0보다 작으면 부정적인 감정을 나타냅니다.

Go

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Go API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

import (
	"context"
	"fmt"
	"io"

	language "cloud.google.com/go/language/apiv2"
	"cloud.google.com/go/language/apiv2/languagepb"
)

// analyzeSentiment sends a string of text to the Cloud Natural Language API to
// assess the sentiment of the text.
func analyzeSentiment(w io.Writer, text string) error {
	ctx := context.Background()

	// Initialize client.
	client, err := language.NewClient(ctx)
	if err != nil {
		return err
	}
	defer client.Close()

	resp, err := client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_Content{
				Content: text,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
		EncodingType: languagepb.EncodingType_UTF8,
	})

	if err != nil {
		return fmt.Errorf("AnalyzeSentiment: %w", err)
	}
	fmt.Fprintf(w, "Response: %q\n", resp)

	return nil
}

Java

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Java API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Instantiate the Language client com.google.cloud.language.v2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();
  AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
  Sentiment sentiment = response.getDocumentSentiment();
  if (sentiment == null) {
    System.out.println("No sentiment found");
  } else {
    System.out.printf("Sentiment magnitude: %.3f\n", sentiment.getMagnitude());
    System.out.printf("Sentiment score: %.3f\n", sentiment.getScore());
  }
  return sentiment;
}

Python

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Python API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import language_v2

def sample_analyze_sentiment(text_content: str = "I am so happy and joyful.") -> None:
    """
    Analyzes Sentiment in a string.

    Args:
      text_content: The text content to analyze.
    """

    client = language_v2.LanguageServiceClient()

    # text_content = 'I am so happy and joyful.'

    # Available types: PLAIN_TEXT, HTML
    document_type_in_plain_text = language_v2.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language_code = "en"
    document = {
        "content": text_content,
        "type_": document_type_in_plain_text,
        "language_code": language_code,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    # See https://cloud.google.com/natural-language/docs/reference/rest/v2/EncodingType.
    encoding_type = language_v2.EncodingType.UTF8

    response = client.analyze_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Get overall sentiment of the input document
    print(f"Document sentiment score: {response.document_sentiment.score}")
    print(f"Document sentiment magnitude: {response.document_sentiment.magnitude}")
    # Get sentiment for all sentences in the document
    for sentence in response.sentences:
        print(f"Sentence text: {sentence.text.content}")
        print(f"Sentence sentiment score: {sentence.sentiment.score}")
        print(f"Sentence sentiment magnitude: {sentence.sentiment.magnitude}")

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.
    print(f"Language of the text: {response.language_code}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 자연 언어 참조 문서를 참조하세요.

Cloud Storage에서 감정 분석

편의를 위해 Natural Language API는 요청 본문의 파일 내용을 보낼 필요 없이 Cloud Storage에 있는 파일에서 직접 항목 분석을 수행할 수 있습니다.

다음은 Cloud Storage에 있는 파일에서 감정 분석을 수행하는 예입니다.

프로토콜

Cloud Storage에 저장된 문서에서 감정을 분석하려면 documents:analyzeSentiment 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/v2/documents:analyzeSentiment"

document.language_code를 지정하지 않으면 언어가 자동으로 감지됩니다. Natural Language API에서 지원되는 언어에 대한 자세한 내용은 언어 지원을 참조하세요. 요청 본문 구성에 대한 자세한 내용은 Document 참조 문서를 확인하세요.

요청이 성공하면 서버가 200 OK HTTP 상태 코드와 응답을 JSON 형식으로 반환합니다.

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language_code": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score가 0보다 크면 긍정적인 감정을 나타내며 0보다 작으면 부정적인 감정을 나타냅니다.

gcloud

자세한 내용은 analyze-sentiment 명령어를 참조하세요.

Cloud Storage의 파일에 대한 감정 분석을 수행하려면 gcloud 명령줄 도구와 --content-file 플래그를 사용하여 분석할 콘텐츠가 포함된 파일 경로를 식별합니다.

gcloud ml language analyze-sentiment --content-file=gs://YOUR_BUCKET_NAME/YOUR_FILE_NAME

요청이 성공하면 서버는 JSON 형식의 응답을 반환합니다.

{
  "documentSentiment": {
    "magnitude": 0.8,
    "score": 0.8
  },
  "language": "en",
  "sentences": [
    {
      "text": {
        "content": "Enjoy your vacation!",
        "beginOffset": 0
      },
      "sentiment": {
        "magnitude": 0.8,
        "score": 0.8
      }
    }
  ]
}

documentSentiment.score가 0보다 크면 긍정적인 감정을 나타내며 0보다 작으면 부정적인 감정을 나타냅니다.

Go

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Go API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


func analyzeSentimentFromGCS(ctx context.Context, gcsURI string) (*languagepb.AnalyzeSentimentResponse, error) {
	return client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		Document: &languagepb.Document{
			Source: &languagepb.Document_GcsContentUri{
				GcsContentUri: gcsURI,
			},
			Type: languagepb.Document_PLAIN_TEXT,
		},
	})
}

Java

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Java API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// Instantiate the Language client com.google.cloud.language.v2.LanguageServiceClient
try (LanguageServiceClient language = LanguageServiceClient.create()) {
  Document doc =
      Document.newBuilder().setGcsContentUri(gcsUri).setType(Type.PLAIN_TEXT).build();
  AnalyzeSentimentResponse response = language.analyzeSentiment(doc);
  Sentiment sentiment = response.getDocumentSentiment();
  if (sentiment == null) {
    System.out.println("No sentiment found");
  } else {
    System.out.printf("Sentiment magnitude : %.3f\n", sentiment.getMagnitude());
    System.out.printf("Sentiment score : %.3f\n", sentiment.getScore());
  }
  return sentiment;
}

Node.js

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Node.js API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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

// 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 the sentiment of the document
const [result] = await client.analyzeSentiment({document});

const sentiment = result.documentSentiment;
console.log('Document sentiment:');
console.log(`  Score: ${sentiment.score}`);
console.log(`  Magnitude: ${sentiment.magnitude}`);

const sentences = result.sentences;
sentences.forEach(sentence => {
  console.log(`Sentence: ${sentence.text.content}`);
  console.log(`  Score: ${sentence.sentiment.score}`);
  console.log(`  Magnitude: ${sentence.sentiment.magnitude}`);
});

Python

Natural Language용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Natural Language 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Natural Language Python API 참조 문서를 참조하세요.

Natural Language에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

from google.cloud import language_v2

def sample_analyze_sentiment(
    gcs_content_uri: str = "gs://cloud-samples-data/language/sentiment-positive.txt",
) -> None:
    """
    Analyzes Sentiment in text file stored in Cloud Storage.

    Args:
      gcs_content_uri: Google Cloud Storage URI where the file content is located.
        e.g. gs://[Your Bucket]/[Path to File]
    """

    client = language_v2.LanguageServiceClient()

    # Available types: PLAIN_TEXT, HTML
    document_type_in_plain_text = language_v2.Document.Type.PLAIN_TEXT

    # Optional. If not specified, the language is automatically detected.
    # For list of supported languages:
    # https://cloud.google.com/natural-language/docs/languages
    language_code = "en"
    document = {
        "gcs_content_uri": gcs_content_uri,
        "type_": document_type_in_plain_text,
        "language_code": language_code,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    # See https://cloud.google.com/natural-language/docs/reference/rest/v2/EncodingType.
    encoding_type = language_v2.EncodingType.UTF8

    response = client.analyze_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Get overall sentiment of the input document
    print(f"Document sentiment score: {response.document_sentiment.score}")
    print(f"Document sentiment magnitude: {response.document_sentiment.magnitude}")
    # Get sentiment for all sentences in the document
    for sentence in response.sentences:
        print(f"Sentence text: {sentence.text.content}")
        print(f"Sentence sentiment score: {sentence.sentiment.score}")
        print(f"Sentence sentiment magnitude: {sentence.sentiment.magnitude}")

    # Get the language of the text, which will be the same as
    # the language specified in the request or, if not specified,
    # the automatically-detected language.
    print(f"Language of the text: {response.language_code}")

추가 언어

C#: 클라이언트 라이브러리 페이지의 C# 설정 안내를 따른 후 .NET용 자연 언어 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 후 PHP용 자연 언어 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 후 Ruby용 자연 언어 참조 문서를 참조하세요.