分析實體情緒

實體情緒分析結合實體分析和情緒分析,嘗試判斷文字中對實體表達的情緒 (正面或負面)。實體情緒會以數值分數和強度值表示,並針對實體的每次提及進行判斷。接著,這些分數會匯總成實體的整體情緒分數和強度。如要瞭解如何解讀分析中包含的 score 和 magnitude 情緒值,請參閱「解讀情緒分析值」。

以下範例說明如何查詢 analyzeEntitySentiment 方法。每份文件都必須分別提交要求。

分析實體情緒

以下示範如何分析以字串提供的實體情緒:

通訊協定

如要分析文件中的實體情緒,請向 documents:analyzeEntitySentiment 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 "{
  '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 CLI,並透過 --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."

Go

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Go API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Java API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (com.google.cloud.language.v1.LanguageServiceClient language =
    com.google.cloud.language.v1.LanguageServiceClient.create()) {
  com.google.cloud.language.v1.Document doc =
      com.google.cloud.language.v1.Document.newBuilder().setContent(text)
          .setType(com.google.cloud.language.v1.Document.Type.PLAIN_TEXT).build();
  AnalyzeEntitySentimentRequest request =
      AnalyzeEntitySentimentRequest.newBuilder()
          .setDocument(doc)
          .setEncodingType(com.google.cloud.language.v1.EncodingType.UTF16)
          .build();
  // Detect entity sentiments in the given string
  AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
  // Print the response
  for (com.google.cloud.language.v1.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 (com.google.cloud.language.v1.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

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Node.js API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Python API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.cloud import language_v1


def sample_analyze_entity_sentiment(text_content):
    """
    Analyzing Entity Sentiment in a String

    Args:
      text_content The text content to analyze
    """

    client = language_v1.LanguageServiceClient()

    # text_content = 'Grapes are good. Bananas are bad.'

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

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

    response = client.analyze_entity_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Loop through entitites returned from the API
    for entity in response.entities:
        print(f"Representative name for the entity: {entity.name}")
        # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al
        print(f"Entity type: {language_v1.Entity.Type(entity.type_).name}")
        # Get the salience score associated with the entity in the [0, 1.0] range
        print(f"Salience score: {entity.salience}")
        # Get the aggregate sentiment expressed for this entity in the provided document.
        sentiment = entity.sentiment
        print(f"Entity sentiment score: {sentiment.score}")
        print(f"Entity sentiment magnitude: {sentiment.magnitude}")
        # Loop over the metadata associated with entity. For many known entities,
        # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid).
        # Some entity types may have additional metadata, e.g. ADDRESS entities
        # may have metadata for the address street_name, postal_code, et al.
        for metadata_name, metadata_value in entity.metadata.items():
            print(f"{metadata_name} = {metadata_value}")

        # Loop over the mentions of this entity in the input document.
        # The API currently supports proper noun mentions.
        for mention in entity.mentions:
            print(f"Mention text: {mention.text.content}")
            # Get the mention type, e.g. PROPER for proper noun
            print(
                "Mention type: {}".format(
                    language_v1.EntityMention.Type(mention.type_).name
                )
            )

    # 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}")

其他語言

C#:請按照用戶端程式庫頁面上的 C# 設定操作說明完成相關步驟,然後參閱 .NET 適用的自然語言參考文件。

PHP:請按照用戶端程式庫頁面上的 PHP 設定操作說明完成相關步驟,然後參閱 PHP 適用的自然語言參考文件。

Ruby:請按照用戶端程式庫頁面上的 Ruby 設定操作說明完成相關步驟,然後參閱 Ruby 適用的自然語言參考文件。

分析 Cloud Storage 中的實體情緒

以下範例說明如何分析 Cloud Storage 文字檔案中儲存的實體情緒:

通訊協定

如要分析 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 CLI,並透過 --content 旗標指定要分析的內容:

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

Java

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Java API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

// Instantiate the Language client com.google.cloud.language.v1.LanguageServiceClient
try (com.google.cloud.language.v1.LanguageServiceClient language =
    com.google.cloud.language.v1.LanguageServiceClient.create()) {
  com.google.cloud.language.v1.Document doc =
      com.google.cloud.language.v1.Document.newBuilder().setGcsContentUri(gcsUri)
          .setType(com.google.cloud.language.v1.Document.Type.PLAIN_TEXT).build();
  AnalyzeEntitySentimentRequest request =
      AnalyzeEntitySentimentRequest.newBuilder()
          .setDocument(doc)
          .setEncodingType(com.google.cloud.language.v1.EncodingType.UTF16)
          .build();
  // Detect entity sentiments in the given file
  AnalyzeEntitySentimentResponse response = language.analyzeEntitySentiment(request);
  // Print the response
  for (com.google.cloud.language.v1.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 (com.google.cloud.language.v1.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

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Node.js API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

如要瞭解如何安裝及使用 Natural Language 的用戶端程式庫,請參閱「Natural Language 用戶端程式庫」。詳情請參閱 Natural Language Python API 參考文件。

如要向自然語言進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

from google.cloud import language_v1


def sample_analyze_entity_sentiment(gcs_content_uri):
    """
    Analyzing Entity 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/entity-sentiment.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_entity_sentiment(
        request={"document": document, "encoding_type": encoding_type}
    )
    # Loop through entitites returned from the API
    for entity in response.entities:
        print(f"Representative name for the entity: {entity.name}")
        # Get entity type, e.g. PERSON, LOCATION, ADDRESS, NUMBER, et al
        print(f"Entity type: {language_v1.Entity.Type(entity.type_).name}")
        # Get the salience score associated with the entity in the [0, 1.0] range
        print(f"Salience score: {entity.salience}")
        # Get the aggregate sentiment expressed for this entity in the provided document.
        sentiment = entity.sentiment
        print(f"Entity sentiment score: {sentiment.score}")
        print(f"Entity sentiment magnitude: {sentiment.magnitude}")
        # Loop over the metadata associated with entity. For many known entities,
        # the metadata is a Wikipedia URL (wikipedia_url) and Knowledge Graph MID (mid).
        # Some entity types may have additional metadata, e.g. ADDRESS entities
        # may have metadata for the address street_name, postal_code, et al.
        for metadata_name, metadata_value in entity.metadata.items():
            print(f"{metadata_name} = {metadata_value}")

        # Loop over the mentions of this entity in the input document.
        # The API currently supports proper noun mentions.
        for mention in entity.mentions:
            print(f"Mention text: {mention.text.content}")
            # Get the mention type, e.g. PROPER for proper noun
            print(
                "Mention type: {}".format(
                    language_v1.EntityMention.Type(mention.type_).name
                )
            )

    # 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}")

其他語言

C#:請按照用戶端程式庫頁面上的 C# 設定操作說明完成相關步驟,然後參閱 .NET 適用的自然語言參考文件。

PHP:請按照用戶端程式庫頁面上的 PHP 設定操作說明完成相關步驟,然後參閱 PHP 適用的自然語言參考文件。

Ruby:請按照用戶端程式庫頁面上的 Ruby 設定操作說明完成相關步驟,然後參閱 Ruby 適用的自然語言參考文件。