分析情緒

情緒分析會檢查指定的文字內容,進而識別文字內容的主要情緒主張,特別是判斷撰寫者的態度為正面、負面或中立。情緒分析是透過 analyzeSentiment 方法執行。如需有關 Natural Language API 支援哪些語言的資訊,請參閱語言支援。如要瞭解如何解讀分析中的 scoremagnitude 情緒值,請參閱「情緒分析值說明」。

本節示範幾種偵測文件中情緒的方法。請為每份文件分別提交要求。

分析字串中的情緒

以下示範如何針對直接傳送至 Natural Language API 的文字字串執行情緒分析:

通訊協定

POST 要求,並提供適當的要求主體,如同下列範例所示。documents:analyzeSentiment

範例使用 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 會以大於零的數值來表示正面情緒,小於零的數值則表示負面情緒。

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 會以大於零的數值來表示正面情緒,小於零的數值則表示負面情緒。

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 適用的 Natural Language 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明操作, 然後前往 PHP 適用的 Natural Language 參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Natural Language 參考說明文件。

分析 Cloud Storage 中的情緒

為方便起見,Natural Language API 可以直接對 Cloud Storage 中的檔案執行情緒分析,您無需在要求內容中傳送檔案的內容。

以下示範如何對位於 Cloud Storage 的檔案執行情緒分析。

通訊協定

POST 要求,並提供適當的要求主體及文件路徑,如同下列範例所示。POSTdocuments:analyzeSentiment

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 會以大於零的數值來表示正面情緒,小於零的數值則表示負面情緒。

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 會以大於零的數值來表示正面情緒,小於零的數值則表示負面情緒。

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 適用的 Natural Language 參考說明文件

PHP: 請按照用戶端程式庫頁面的 PHP 設定說明操作, 然後前往 PHP 適用的 Natural Language 參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明 操作,然後前往 Ruby 適用的 Natural Language 參考說明文件。