分析情感

情感分析检查给定文本,并确定文本中的普遍情绪看法,尤其是确定作者的态度是正面、负面还是中立的。情感分析是通过 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 用大于零的值指示积极情感,用小于零的值指示消极情感。

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 中的文件执行情感分析。

协议

如需分析 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 用大于零的值指示积极情感,用小于零的值指示消极情感。

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 参考文档。