感情分析

コレクションでコンテンツを整理 必要に応じて、コンテンツの保存と分類を行います。

感情分析は、指定されたテキストを調べて、そのテキストの背景にある感情的な考え方を分析します。具体的には、執筆者の考え方がポジティブか、ネガティブか、ニュートラルかを判断します。感情分析を実行するには analyzeSentiment メソッドを使用します。Natural Language API でサポートされる言語については、言語のサポートをご覧ください。分析に含まれる感情の値 score および magnitude を解釈する方法については、感情分析の値の解釈をご覧ください。

このセクションでは、ドキュメント内の感情を検出するいくつかの方法を説明します。リクエストは、ドキュメントごとに送信する必要があります。

文字列の感情分析

Natural Language API に直接送信されたテキスト文字列に対して感情分析を行う例を次に示します。

プロトコル

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

この例では、Google Cloud Platform の gcloud CLI を使用してプロジェクト用に設定されたサービス アカウントのアクセス トークンを取得するために、gcloud auth application-default print-access-token コマンドを使用しています。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/v1/documents:analyzeSentiment"

document.language を指定しない場合は、言語が自動的に検出されます。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


func analyzeSentiment(ctx context.Context, client *language.Client, text string) (*languagepb.AnalyzeSentimentResponse, error) {
	return client.AnalyzeSentiment(ctx, &languagepb.AnalyzeSentimentRequest{
		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();
  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

// 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 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


from google.cloud import language_v1
import six

def sample_analyze_sentiment(content):

    client = language_v1.LanguageServiceClient()

    # content = 'Your text to analyze, e.g. Hello, world!'

    if isinstance(content, six.binary_type):
        content = content.decode("utf-8")

    type_ = language_v1.Document.Type.PLAIN_TEXT
    document = {"type_": type_, "content": content}

    response = client.analyze_sentiment(request={"document": document})
    sentiment = response.document_sentiment
    print("Score: {}".format(sentiment.score))
    print("Magnitude: {}".format(sentiment.magnitude))

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Natural Language リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Natural Language リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby の Natural Language のリファレンス ドキュメントをご覧ください。

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/v1/documents:analyzeSentiment"

document.language を指定しない場合は、言語が自動的に検出されます。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 コマンドをご覧ください。

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


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

// 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();
  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

// 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 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

from google.cloud import language_v1

def sample_analyze_sentiment(gcs_content_uri):
    """
    Analyzing 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_v1.LanguageServiceClient()

    # gcs_content_uri = 'gs://cloud-samples-data/language/sentiment-positive.txt'

    # Available types: PLAIN_TEXT, HTML
    type_ = language_v1.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 = "en"
    document = {
        "gcs_content_uri": gcs_content_uri,
        "type_": type_,
        "language": language,
    }

    # Available values: NONE, UTF8, UTF16, UTF32
    encoding_type = language_v1.EncodingType.UTF8

    response = client.analyze_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Get overall sentiment of the input document
    print("Document sentiment score: {}".format(response.document_sentiment.score))
    print(
        "Document sentiment magnitude: {}".format(response.document_sentiment.magnitude)
    )
    # Get sentiment for all sentences in the document
    for sentence in response.sentences:
        print("Sentence text: {}".format(sentence.text.content))
        print("Sentence sentiment score: {}".format(sentence.sentiment.score))
        print("Sentence sentiment magnitude: {}".format(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("Language of the text: {}".format(response.language))

その他の言語

C#: クライアント ライブラリ ページの C# の設定手順を行ってから、.NET 用の Natural Language リファレンス ドキュメントをご覧ください。

PHP: クライアント ライブラリ ページの PHP の設定手順を行ってから、PHP 用の Natural Language リファレンス ドキュメントをご覧ください。

Ruby: クライアント ライブラリ ページの Ruby の設定手順を行ってから、Ruby の Natural Language のリファレンス ドキュメントをご覧ください。