Melakukan analisis sentimen menggunakan library klien

Halaman ini menunjukkan cara memulai Cloud Natural Language API dalam bahasa pemrograman favorit Anda menggunakan Library Klien Google Cloud.

Sebelum memulai

  1. Sign in to your Google Account.

    If you don't already have one, sign up for a new account.

  2. Install the Google Cloud CLI.

  3. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  4. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  5. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Natural Language API:

    gcloud services enable language.googleapis.com
  8. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  9. Install the Google Cloud CLI.

  10. Jika Anda menggunakan penyedia identitas (IdP) eksternal, Anda harus login ke gcloud CLI dengan identitas gabungan Anda terlebih dahulu.

  11. Untuk melakukan inisialisasi gcloud CLI, jalankan perintah berikut:

    gcloud init
  12. Create or select a Google Cloud project.

    • Create a Google Cloud project:

      gcloud projects create PROJECT_ID

      Replace PROJECT_ID with a name for the Google Cloud project you are creating.

    • Select the Google Cloud project that you created:

      gcloud config set project PROJECT_ID

      Replace PROJECT_ID with your Google Cloud project name.

  13. Verify that billing is enabled for your Google Cloud project.

  14. Enable the Cloud Natural Language API:

    gcloud services enable language.googleapis.com
  15. Create local authentication credentials for your user account:

    gcloud auth application-default login

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

  16. Menginstal library klien

    Go

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

    Java

    If you are using Maven, add the following to your pom.xml file. For more information about BOMs, see The Google Cloud Platform Libraries BOM.

    <dependencyManagement>
      <dependencies>
        <dependency>
          <groupId>com.google.cloud</groupId>
          <artifactId>libraries-bom</artifactId>
          <version>26.66.0</version>
          <type>pom</type>
          <scope>import</scope>
        </dependency>
      </dependencies>
    </dependencyManagement>
    
    <dependencies>
      <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-language</artifactId>
      </dependency>
    </dependencies>

    If you are using Gradle, add the following to your dependencies:

    implementation 'com.google.cloud:google-cloud-language:2.73.0'

    If you are using sbt, add the following to your dependencies:

    libraryDependencies += "com.google.cloud" % "google-cloud-language" % "2.73.0"

    If you're using Visual Studio Code, IntelliJ, or Eclipse, you can add client libraries to your project using the following IDE plugins:

    The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

    Node.js

    Sebelum menginstal library, pastikan Anda telah menyiapkan lingkungan untuk pengembangan Node.js.

    npm install @google-cloud/language

    Python

    Sebelum menginstal library, pastikan Anda telah menyiapkan lingkungan untuk pengembangan Python.

    pip install --upgrade google-cloud-language

    Menganalisis beberapa teks

    Sekarang Anda dapat menggunakan Natural Language API untuk menganalisis beberapa teks. Jalankan kode berikut untuk melakukan analisis sentimen teks pertama Anda:

    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"
    	"cloud.google.com/go/language/apiv1/languagepb"
    )
    
    func main() {
    	ctx := context.Background()
    
    	// Creates a client.
    	client, err := language.NewClient(ctx)
    	if err != nil {
    		log.Fatalf("Failed to create client: %v", err)
    	}
    	defer client.Close()
    
    	// 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

    Sebelum menjalankan contoh, pastikan Anda telah menyiapkan lingkungan untuk pengembangan 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}`);
    }

    Python

    Sebelum menjalankan contoh, pastikan Anda telah menyiapkan lingkungan untuk pengembangan Python.

    # Imports the Google Cloud client library.
    from google.cloud import language_v1
    
    # Instantiates a client.
    client = language_v1.LanguageServiceClient()
    
    # The text to analyze.
    text = "Hello, world!"
    document = language_v1.types.Document(
        content=text, type_=language_v1.types.Document.Type.PLAIN_TEXT
    )
    
    # Detects the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment
    
    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")

    Selamat! Anda telah mengirimkan permintaan pertama ke Natural Language API.

    Bagaimana hasilnya?

    Pembersihan

    Agar tidak menimbulkan biaya pada akun Google Cloud Anda untuk resource yang digunakan di halaman ini, hapus project Google Cloud yang berisi resource tersebut.

    Langkah berikutnya