클라이언트 라이브러리를 사용한 감정 분석 수행

이 페이지에서는 Google Cloud 클라이언트 라이브러리를 사용하여 선호하는 프로그래밍 언어로 Cloud Natural Language API를 시작하는 방법을 보여줍니다.

시작하기 전에

  1. Google 계정에 로그인합니다.

    아직 계정이 없으면 새 계정을 등록하세요.

  2. Google Cloud CLI를 설치합니다.

  3. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  4. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  5. 프로젝트를 만들거나 Google Cloud 선택합니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택할 수 있습니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할 (roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기.
    • 프로젝트 만들기: Google Cloud

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 생성한 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID를 프로젝트 이름으로 바꿉니다. Google Cloud

  6. 프로젝트에 결제가 사용 설정되어 있는지 확인합니다 Google Cloud .

  7. Cloud Natural Language API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 역할 (roles/serviceusage.serviceUsageAdmin)이 포함된 서비스 사용량 관리자 IAM serviceusage.services.enable 권한이 필요합니다. 역할 부여 방법 알아보기.

    gcloud services enable language.googleapis.com
  8. gcloud auth application-default login

    인증 오류가 반환되고 외부 ID 공급업체(IdP)를 사용하는 경우 제휴 ID로 gcloud CLI에 로그인했는지 확인합니다.

  9. Google Cloud CLI를 설치합니다.

  10. 외부 ID 공급업체(IdP)를 사용하는 경우 먼저 제휴 ID로 gcloud CLI에 로그인해야 합니다.

  11. gcloud CLI를 초기화하려면, 다음 명령어를 실행합니다.

    gcloud init
  12. 프로젝트를 만들거나 Google Cloud 선택합니다.

    프로젝트를 선택하거나 만드는 데 필요한 역할

    • 프로젝트 선택: 프로젝트를 선택하는 데 특정 IAM 역할이 필요하지 않습니다. 역할이 부여된 프로젝트를 선택할 수 있습니다.
    • 프로젝트 만들기: 프로젝트를 만들려면 resourcemanager.projects.create 권한이 포함된 프로젝트 생성자 역할 (roles/resourcemanager.projectCreator)이 필요합니다. 역할 부여 방법 알아보기.
    • 프로젝트 만들기: Google Cloud

      gcloud projects create PROJECT_ID

      PROJECT_ID를 만들려는 Google Cloud 프로젝트의 이름으로 바꿉니다.

    • 생성한 Google Cloud 프로젝트를 선택합니다.

      gcloud config set project PROJECT_ID

      PROJECT_ID를 프로젝트 이름으로 바꿉니다. Google Cloud

  13. 프로젝트에 결제가 사용 설정되어 있는지 확인합니다 Google Cloud .

  14. Cloud Natural Language API를 사용 설정합니다.

    API 사용 설정에 필요한 역할

    API를 사용 설정하려면 역할 (roles/serviceusage.serviceUsageAdmin)이 포함된 서비스 사용량 관리자 IAM serviceusage.services.enable 권한이 필요합니다. 역할 부여 방법 알아보기.

    gcloud services enable language.googleapis.com
  15. gcloud auth application-default login

    인증 오류가 반환되고 외부 ID 공급업체(IdP)를 사용하는 경우 제휴 ID로 gcloud CLI에 로그인했는지 확인합니다.

클라이언트 라이브러리 설치

Go

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

Java

Maven을 사용하는 경우 다음 내용을 pom.xml 파일에 추가합니다. BOM에 대한 자세한 내용은 Google Cloud Platform 라이브러리 BOM을 참조하세요.

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>com.google.cloud</groupId>
      <artifactId>libraries-bom</artifactId>
      <version>26.79.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>

Gradle

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

sbt

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

Visual Studio Code 또는 IntelliJ를 사용하는 경우 다음 IDE 플러그인을 사용하여 클라이언트 라이브러리를 프로젝트에 추가할 수 있습니다.

이 플러그인은 서비스 계정의 키 관리와 같은 추가 기능을 제공합니다. 자세한 내용은 각 플러그인의 문서를 참조하세요.

Node.js

라이브러리를 설치하기 전에 Node.js 개발을 위한 환경이 준비됐는지 확인하세요.

npm install @google-cloud/language

Python

라이브러리를 설치하기 전에 Python 개발을 위한 환경이 준비됐는지 확인하세요.

pip install --upgrade google-cloud-language

일부 텍스트 분석

이제 Natural Language API를 사용하여 일부 텍스트를 분석할 수 있습니다. 텍스트 감정 분석을 처음 수행하려면 다음 코드를 실행합니다.

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

예시를 실행하기 전에 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

예시를 실행하기 전에 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}")

수고하셨습니다. 처음으로 요청을 Natural Language API에 보냈습니다.

어땠나요?

삭제

이 페이지에서 사용한 리소스 비용이 계정에 청구되지 않도록 하려면 리소스가 포함된 프로젝트를 삭제하세요. Google Cloud Google Cloud

다음 단계