Natural Language API Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Natural Language API. Read more about the client libraries for Cloud APIs, including the older Google APIs Client Libraries, in Client Libraries Explained.

Installing the client library

C#

For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.Language.V1 -Pre

Go

go get -u cloud.google.com/go/language/apiv1

Java

For more information, see Setting Up a Java Development Environment. 如果您是使用 Maven,請在 pom.xml 檔案中新增以下指令:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-language</artifactId>
  <version>1.61.0</version>
</dependency>
如果您是使用 Gradle,請在相依元件中新增以下指令:
compile 'com.google.cloud:google-cloud-language:1.61.0'
如果您是使用 SBT,請在相依元件中新增以下指令:
libraryDependencies += "com.google.cloud" % "google-cloud-language" % "1.61.0"

如果您使用 IntelliJ 或 Eclipse,可以使用以下 IDE 外掛程式將用戶端程式庫加入專案中:

外掛程式還提供其他功能,例如服務帳戶適用的金鑰管理。詳情請參閱各外掛程式的說明文件。

Node.js

For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/language

PHP

composer require google/cloud-language

Python

For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-language

Ruby

For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-language

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP 主控台

  1. 在 GCP 主控台中,前往「Create service account key」(建立服務帳戶金鑰) 頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面
  2. 從 [Service account] (服務帳戶) 清單中選取 [New service account] (新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 從 [Role] (角色) 清單中,選取 [Project] (專案) > [Owner] (擁有者)

    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。以後您可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  5. 點選 [建立]。一個包含您金鑰的 JSON 檔案會下載到電腦中。

指令列

您可以使用本機電腦上的 Cloud SDK,或在 Cloud Shell 內執行下列指令。

  1. 建立服務帳戶。將 [NAME] 換成服務帳戶的名稱。

    gcloud iam service-accounts create [NAME]
  2. 向服務帳戶授予權限。用您的專案 ID 取代 [PROJECT_ID]

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。您稍後可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  3. 產生金鑰檔案。用金鑰檔案的名稱取代 [FILE_NAME]

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID].iam.gserviceaccount.com

設定環境變數 GOOGLE_APPLICATION_CREDENTIALS 來為應用程式程式碼提供驗證憑證。 將 [PATH] 改成包含您的服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 改成檔案名稱。 此變數僅適用於您目前的殼層工作階段,所以如果您開啟新的工作階段,請再次設定變數。

Linux 或 macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"

Windows

使用 PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

例如:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

使用命令提示字元:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

Using the client library

The following example shows how to use the client library.

C#


using Google.Cloud.Language.V1;
using System;

namespace GoogleCloudSamples
{
    public class QuickStart
    {
        public static void Main(string[] args)
        {
            // The text to analyze.
            string text = "Hello World!";
            var client = LanguageServiceClient.Create();
            var response = client.AnalyzeSentiment(new Document()
            {
                Content = text,
                Type = Document.Types.Type.PlainText
            });
            var sentiment = response.DocumentSentiment;
            Console.WriteLine($"Score: {sentiment.Score}");
            Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
        }
    }
}

Go


// Sample language-quickstart uses the Google Cloud Natural API to analyze the
// sentiment of "Hello, world!".
package main

import (
	"context"
	"fmt"
	"log"

	language "cloud.google.com/go/language/apiv1"
	languagepb "google.golang.org/genproto/googleapis/cloud/language/v1"
)

func main() {
	ctx := context.Background()

	// Creates a client.
	client, err := language.NewClient(ctx)
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	// Sets the text to analyze.
	text := "Hello, world!"

	// Detects the sentiment of the text.
	sentiment, 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 {
		log.Fatalf("Failed to analyze text: %v", err)
	}

	fmt.Printf("Text: %v\n", text)
	if sentiment.DocumentSentiment.Score >= 0 {
		fmt.Println("Sentiment: positive")
	} else {
		fmt.Println("Sentiment: negative")
	}
}

Java

// Imports the Google Cloud client library
import com.google.cloud.language.v1.Document;
import com.google.cloud.language.v1.Document.Type;
import com.google.cloud.language.v1.LanguageServiceClient;
import com.google.cloud.language.v1.Sentiment;

public class QuickstartSample {
  public static void main(String... args) throws Exception {
    // Instantiates a client
    try (LanguageServiceClient language = LanguageServiceClient.create()) {

      // The text to analyze
      String text = "Hello, world!";
      Document doc = Document.newBuilder()
          .setContent(text).setType(Type.PLAIN_TEXT).build();

      // Detects the sentiment of the text
      Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

      System.out.printf("Text: %s%n", text);
      System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());
    }
  }
}

Node.js

async function quickstart() {
  // Imports the Google Cloud client library
  const language = require('@google-cloud/language');

  // Instantiates a client
  const client = new language.LanguageServiceClient();

  // The text to analyze
  const text = 'Hello, world!';

  const document = {
    content: text,
    type: 'PLAIN_TEXT',
  };

  // Detects the sentiment of the text
  const [result] = await client.analyzeSentiment({document: document});
  const sentiment = result.documentSentiment;

  console.log(`Text: ${text}`);
  console.log(`Sentiment score: ${sentiment.score}`);
  console.log(`Sentiment magnitude: ${sentiment.magnitude}`);
}

PHP

# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';

# Imports the Google Cloud client library
use Google\Cloud\Language\LanguageClient;

# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';

# Instantiates a client
$language = new LanguageClient([
    'projectId' => $projectId
]);

# The text to analyze
$text = 'Hello, world!';

# Detects the sentiment of the text
$annotation = $language->analyzeSentiment($text);
$sentiment = $annotation->sentiment();

echo 'Text: ' . $text . '
Sentiment: ' . $sentiment['score'] . ', ' . $sentiment['magnitude'];

Python

# Imports the Google Cloud client library
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types

# Instantiates a client
client = language.LanguageServiceClient()

# The text to analyze
text = u'Hello, world!'
document = types.Document(
    content=text,
    type=enums.Document.Type.PLAIN_TEXT)

# Detects the sentiment of the text
sentiment = client.analyze_sentiment(document=document).document_sentiment

print('Text: {}'.format(text))
print('Sentiment: {}, {}'.format(sentiment.score, sentiment.magnitude))

Ruby

# Imports the Google Cloud client library
require "google/cloud/language"

# Instantiates a client
language = Google::Cloud::Language.new

# The text to analyze
text = "Hello, world!"

# Detects the sentiment of the text
response = language.analyze_sentiment content: text, type: :PLAIN_TEXT

# Get document sentiment from response
sentiment = response.document_sentiment

puts "Text: #{text}"
puts "Score: #{sentiment.score}, #{sentiment.magnitude}"

Additional resources

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Natural Language API
需要協助嗎?請前往我們的支援網頁