分析情感

情感分析检查给定文本,并确定文本中的普遍情绪看法,尤其是确定作者的态度是正面、负面还是中立的。情感分析是通过 analyzeSentiment 方法执行的。有关 Natural Language API 支持哪些语言的信息,请参阅语言支持。如需了解如何解读分析中包含的 scoremagnitude 情感值,请参阅解读情感分析值

本部分介绍几种检测文档情感的方法。

分析字符串中的情感

下面的示例展示如何对直接发送至 Natural Language API 的文本字符串执行情感分析:

协议

如要分析文档中的情感,请按照下面示例中所示,向 documents:analyzeSentiment REST 方法发出 POST 请求,并提供相应的请求正文。

此示例使用 gcloud auth application-default print-access-token 命令获取为使用 Google Cloud Platform Cloud SDK 的项目设置的服务帐号的访问令牌。如需了解有关安装 Cloud SDK 以及使用服务帐号设置项目的说明,请参阅快速入门

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

如果请求成功,则服务器以 JSON 格式返回 200 OK HTTP 状态代码和响应:

{
  "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 命令行工具并使用 --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 用大于零的值指示积极情感,用小于零的值指示消极情感。

C#

private static void AnalyzeSentimentFromText(string text)
{
    var client = LanguageServiceClient.Create();
    var response = client.AnalyzeSentiment(new Document()
    {
        Content = text,
        Type = Document.Types.Type.PlainText
    });
    WriteSentiment(response.DocumentSentiment, response.Sentences);
}

private static void WriteSentiment(Sentiment sentiment,
    RepeatedField<Sentence> sentences)
{
    Console.WriteLine("Overall document sentiment:");
    Console.WriteLine($"\tScore: {sentiment.Score}");
    Console.WriteLine($"\tMagnitude: {sentiment.Magnitude}");
    Console.WriteLine("Sentence level sentiment:");
    foreach (var sentence in sentences)
    {
        Console.WriteLine($"\t{sentence.Text.Content}: "
            + $"({sentence.Sentiment.Score})");
    }
}

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}`);
});

PHP

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\V1beta2\Document;
use Google\Cloud\Language\V1beta2\Document\Type;
use Google\Cloud\Language\V1beta2\LanguageServiceClient;

/**
 * Find the sentiment in text.
 * ```
 * analyze_sentiment('Do you know the way to San Jose?');
 * ```
 *
 * @param string $text The text to analyze.
 * @param string $projectId (optional) Your Google Cloud Project ID
 *
 */
function analyze_sentiment($text, $projectId = null)
{
    $languageServiceClient = new LanguageServiceClient(['projectId' => $projectId]);
    try {
        // Create a new Document
        $document = new Document();
        // Pass GCS URI and set document type to PLAIN_TEXT
        $document->setContent($text)->setType(Type::PLAIN_TEXT);
        // Call the analyzeSentiment function
        $response = $languageServiceClient->analyzeSentiment($document);
        $document_sentiment = $response->getDocumentSentiment();
        // Print document information
        printf('Document Sentiment:' . PHP_EOL);
        printf('  Magnitude: %s' . PHP_EOL, $document_sentiment->getMagnitude());
        printf('  Score: %s' . PHP_EOL, $document_sentiment->getScore());
        printf(PHP_EOL);
        $sentences = $response->getSentences();
        foreach ($sentences as $sentence) {
            printf('Sentence: %s' . PHP_EOL, $sentence->getText()->getContent());
            printf('Sentence Sentiment:' . PHP_EOL);
            $sentiment = $sentence->getSentiment();
            if ($sentiment) {
                printf('Entity Magnitude: %s' . PHP_EOL, $sentiment->getMagnitude());
                printf('Entity Score: %s' . PHP_EOL, $sentiment->getScore());
            }
            print(PHP_EOL);
        }
    } finally {
        $languageServiceClient->close();
    }
}

Python

from google.cloud import language_v1
from google.cloud.language_v1 import enums
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_ = enums.Document.Type.PLAIN_TEXT
    document = {'type': type_, 'content': content}

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

Ruby

# text_content = "Text to run sentiment analysis on"

require "google/cloud/language"

language = Google::Cloud::Language.new

response = language.analyze_sentiment content: text_content, type: :PLAIN_TEXT

sentiment = response.document_sentiment

puts "Overall document sentiment: (#{sentiment.score})"
puts "Sentence level sentiment:"

sentences = response.sentences

sentences.each do |sentence|
  sentiment = sentence.sentiment
  puts "#{sentence.text.content}: (#{sentiment.score})"
end

从 Google Cloud Storage 分析情感

为您方便起见,Natural Language API 可以直接对位于 Google Cloud Storage 的文件执行情感分析,而无需在请求正文中发送文件内容。

以下示例介绍如何对 Cloud Storage 中的文件执行情感分析。

协议

如要分析 Google 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 参考文档。

如果请求成功,则服务器以 JSON 格式返回 200 OK HTTP 状态代码和响应:

{
  "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 命令,了解完整的详细信息。

要对 Google 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 用大于零的值指示积极情感,用小于零的值指示消极情感。

C#

private static void AnalyzeSentimentFromFile(string gcsUri)
{
    var client = LanguageServiceClient.Create();
    var response = client.AnalyzeSentiment(new Document()
    {
        GcsContentUri = gcsUri,
        Type = Document.Types.Type.PlainText
    });
    WriteSentiment(response.DocumentSentiment, response.Sentences);
}
private static void WriteSentiment(Sentiment sentiment,
    RepeatedField<Sentence> sentences)
{
    Console.WriteLine("Overall document sentiment:");
    Console.WriteLine($"\tScore: {sentiment.Score}");
    Console.WriteLine($"\tMagnitude: {sentiment.Magnitude}");
    Console.WriteLine("Sentence level sentiment:");
    foreach (var sentence in sentences)
    {
        Console.WriteLine($"\t{sentence.Text.Content}: "
            + $"({sentence.Sentiment.Score})");
    }
}

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}`);
});

PHP

namespace Google\Cloud\Samples\Language;

use Google\Cloud\Language\V1beta2\Document;
use Google\Cloud\Language\V1beta2\Document\Type;
use Google\Cloud\Language\V1beta2\LanguageServiceClient;

/**
 * Find the sentiment in text stored in a Cloud Storage bucket.
 * ```
 * analyze_sentiment_from_file('my-bucket', 'file_with_text.txt');
 * ```
 *
 * @param string $gcsUri Your Cloud Storage bucket URI
 * @param string $projectId (optional) Your Google Cloud Project ID
 *
 */
function analyze_sentiment_from_file($gcsUri, $projectId = null)
{
    $languageServiceClient = new LanguageServiceClient(['projectId' => $projectId]);
    try {
        // Create a new Document
        $document = new Document();
        // Pass GCS URI and set document type to PLAIN_TEXT
        $document->setGcsContentUri($gcsUri)->setType(Type::PLAIN_TEXT);
        // Call the analyzeSentiment function
        $response = $languageServiceClient->analyzeSentiment($document);
        $document_sentiment = $response->getDocumentSentiment();
        // Print document information
        printf('Document Sentiment:' . PHP_EOL);
        printf('  Magnitude: %s' . PHP_EOL, $document_sentiment->getMagnitude());
        printf('  Score: %s' . PHP_EOL, $document_sentiment->getScore());
        printf(PHP_EOL);
        $sentences = $response->getSentences();
        foreach ($sentences as $sentence) {
            printf('Sentence: %s' . PHP_EOL, $sentence->getText()->getContent());
            printf('Sentence Sentiment:' . PHP_EOL);
            $sentiment = $sentence->getSentiment();
            if ($sentiment) {
                printf('Entity Magnitude: %s' . PHP_EOL, $sentiment->getMagnitude());
                printf('Entity Score: %s' . PHP_EOL, $sentiment->getScore());
            }
            print(PHP_EOL);
        }
    } finally {
        $languageServiceClient->close();
    }
}

Python

from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

gcs_uri = 'gs://cloud-samples-data/language/hello.txt'

client = language.LanguageServiceClient()

# Instantiates a plain text document.
document = types.Document(
    gcs_content_uri=gcs_uri,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects sentiment in the document. You can also analyze HTML with:
#   document.type == enums.Document.Type.HTML
sentiment = client.analyze_sentiment(document).document_sentiment

print('Score: {}'.format(sentiment.score))
print('Magnitude: {}'.format(sentiment.magnitude))

Ruby

# storage_path = "Path to file in Google Cloud Storage, eg. gs://bucket/file"

require "google/cloud/language"

language = Google::Cloud::Language.new

response = language.analyze_sentiment gcs_content_uri: storage_path, type: :PLAIN_TEXT

sentiment = response.document_sentiment

puts "Overall document sentiment: (#{sentiment.score})"
puts "Sentence level sentiment:"

sentences = response.sentences

sentences.each do |sentence|
  sentiment = sentence.sentiment
  puts "#{sentence.text.content}: (#{sentiment.score})"
end