arrow_back

Analyze Sentiment with Natural Language API: Challenge Lab

로그인 가입
700개 이상의 실습 및 과정 이용하기

Analyze Sentiment with Natural Language API: Challenge Lab

실습 45분 universal_currency_alt 크레딧 1개 show_chart 입문
info 이 실습에는 학습을 지원하는 AI 도구가 통합되어 있을 수 있습니다.
700개 이상의 실습 및 과정 이용하기

ARC130

Google Cloud self-paced labs logo

Overview

In a challenge lab you’re given a scenario and a set of tasks. Instead of following step-by-step instructions, you will use the skills learned from the labs in the course to figure out how to complete the tasks on your own! An automated scoring system (shown on this page) will provide feedback on whether you have completed your tasks correctly.

When you take a challenge lab, you will not be taught new Google Cloud concepts. You are expected to extend your learned skills, like changing default values and reading and researching error messages to fix your own mistakes.

To score 100% you must successfully complete all tasks within the time period!

Setup and requirements

Before you click the Start Lab button

Read these instructions. Labs are timed and you cannot pause them. The timer, which starts when you click Start Lab, shows how long Google Cloud resources are made available to you.

This hands-on lab lets you do the lab activities in a real cloud environment, not in a simulation or demo environment. It does so by giving you new, temporary credentials you use to sign in and access Google Cloud for the duration of the lab.

To complete this lab, you need:

  • Access to a standard internet browser (Chrome browser recommended).
Note: Use an Incognito (recommended) or private browser window to run this lab. This prevents conflicts between your personal account and the student account, which may cause extra charges incurred to your personal account.
  • Time to complete the lab—remember, once you start, you cannot pause a lab.
Note: Use only the student account for this lab. If you use a different Google Cloud account, you may incur charges to that account.

Challenge scenario

You recently joined an organization and are working as a junior cloud engineer as part of a team. You have been assigned machine learning (ML) projects and one of your client requirements is to use the Cloud Natural Language API service in Google Cloud to perform tasks for the completion of a project.

You are expected to have the skills and knowledge for the tasks that follow.

Your challenge

For this challenge, you are asked to set up Google Docs and perform sentiment analysis on some reviews provided by customers, analyze syntax and parts of speech using the Natural language API, and create a Natural Language API request for a language other than English.

You need to:

  • Create an API key.
  • Set up Google Docs and call the Natural Language API.
  • Analyze syntax and parts of speech with the Natural Language API.
  • Perform multilingual natural language processing.

For this challenge lab, a virtual machine (VM) instance named has been configured for you to complete tasks 3 and 4.

Some standards you should follow:

  • Ensure that any needed APIs (such as the Cloud Natural Language API) are successfully enabled.

Each task is described in detail below, good luck!

Task 1. Create an API key

  1. For this task, you need to create an API key to use in this and other tasks when sending a request to the Natural Language API.

  2. Save the API key to use in other tasks.

Click Check my progress to verify the objective. Create an API key

Task 2. Set up Google Docs and call the Natural Language API

For this task, you need to set up Google Docs to use the Natural Language API and recognize the sentiment of selected text in a Google Docs document and highlight parts of it based on sentiment.

Text is highlighted in red for negative sentiment, green for positive sentiment, and yellow for neutral sentiment.

  1. Create a new Google Docs document.

  2. Use the following code in Apps Script. In the retrieveSentiment function, replace "your key here" with your actual API key from the Google Cloud Console.

/** * @OnlyCurrentDoc * * The above comment directs Apps Script to limit the scope of file * access for this add-on. It specifies that this add-on will only * attempt to read or modify the files in which the add-on is used, * and not all of the user's files. The authorization request message * presented to users will reflect this limited scope. */ /** * Creates a menu entry in the Google Docs UI when the document is * opened. * */ function onOpen() { var ui = DocumentApp.getUi(); ui.createMenu('Natural Language Tools') .addItem('Mark Sentiment', 'markSentiment') .addToUi(); } /** * Gets the user-selected text and highlights it based on sentiment * with green for positive sentiment, red for negative, and yellow * for neutral. * */ function markSentiment() { var POSITIVE_COLOR = '#00ff00'; // Colors for sentiments var NEGATIVE_COLOR = '#ff0000'; var NEUTRAL_COLOR = '#ffff00'; var NEGATIVE_CUTOFF = -0.2; // Thresholds for sentiments var POSITIVE_CUTOFF = 0.2; var selection = DocumentApp.getActiveDocument().getSelection(); if (selection) { var string = getSelectedText(); var sentiment = retrieveSentiment(string); // Select the appropriate color var color = NEUTRAL_COLOR; if (sentiment <= NEGATIVE_CUTOFF) { color = NEGATIVE_COLOR; } if (sentiment >= POSITIVE_CUTOFF) { color = POSITIVE_COLOR; } // Highlight the text var elements = selection.getSelectedElements(); for (var i = 0; i < elements.length; i++) { if (elements[i].isPartial()) { var element = elements[i].getElement().editAsText(); var startIndex = elements[i].getStartOffset(); var endIndex = elements[i].getEndOffsetInclusive(); element.setBackgroundColor(startIndex, endIndex, color); } else { var element = elements[i].getElement().editAsText(); foundText = elements[i].getElement().editAsText(); foundText.setBackgroundColor(color); } } } } /** * Returns a string with the contents of the selected text. * If no text is selected, returns an empty string. */ function getSelectedText() { var selection = DocumentApp.getActiveDocument().getSelection(); var string = ""; if (selection) { var elements = selection.getSelectedElements(); for (var i = 0; i < elements.length; i++) { if (elements[i].isPartial()) { var element = elements[i].getElement().asText(); var startIndex = elements[i].getStartOffset(); var endIndex = elements[i].getEndOffsetInclusive() + 1; var text = element.getText().substring(startIndex, endIndex); string = string + text; } else { var element = elements[i].getElement(); // Only translate elements that can be edited as text; skip // images and other non-text elements. if (element.editAsText) { string = string + element.asText().getText(); } } } } return string; } /** Given a string, will call the Natural Language API and retrieve * the sentiment of the string. The sentiment will be a real * number in the range -1 to 1, where -1 is highly negative * sentiment and 1 is highly positive. */ function retrieveSentiment(line) { var apiKey = "your key here"; // Replace with your actual API key var apiEndpoint = "https://language.googleapis.com/v1/documents:analyzeSentiment?key=" + apiKey; // Create a structure with the text, its language, its type, // and its encoding var docDetails = { language: 'en-us', type: 'PLAIN_TEXT', content: line }; var nlData = { document: docDetails, encodingType: 'UTF8' }; // Package all of the options and the data together for the call var nlOptions = { method : 'post', contentType: 'application/json', payload : JSON.stringify(nlData) }; // And make the call var response = UrlFetchApp.fetch(apiEndpoint, nlOptions); var data = JSON.parse(response); var sentiment = 0.0; // Ensure all pieces were in the returned value if (data && data.documentSentiment && data.documentSentiment.score){ sentiment = data.documentSentiment.score; } return sentiment; }
  1. Add text to your document. You can use the sample that comes from Charles Dickens' novel, A Tale of Two Cities.

Click Check my progress to verify the objective. Set up Google Docs and call the Natural Language API

Task 3. Analyze syntax and parts of speech with the Natural Language API

To complete this task, connect via SSH to the VM instance named that has been provisioned for you.

  1. Create a JSON file called analyze-request.json using the code that follows.
{ "document":{ "type":"PLAIN_TEXT", "content": "Google, headquartered in Mountain View, unveiled the new Android phone at the Consumer Electronic Show. Sundar Pichai said in his keynote that users love their new Android phones." }, "encodingType": "UTF8" }
  1. Pass your request (along with the API key environment variable you saved earlier in task 1) to the Natural Language API using the curl command or analyze syntax using gcloud ML commands.

  2. Save the response in a file called analyze-response.txt.

Click Check my progress to verify the objective. Analyze syntax and parts of speech with the Natural Language API

Task 4. Perform multilingual natural language processing

To complete this task, connect via SSH to the VM instance named that has been provisioned for you.

  1. Create a JSON file called multi-nl-request.json using the code that follows, which contains a sentence in the French language.
{ "document":{ "type":"PLAIN_TEXT", "content":"Le bureau japonais de Google est situé à Roppongi Hills, Tokyo." } }
  1. Pass your request (along with the API key environment variable you saved earlier in task 1) to the Natural Language API using the curl command or analyze syntax using gcloud ML commands.

  2. Save the output in a file called multi-response.txt.

Click Check my progress to verify the objective. Perform multilingual natural language processing

Congratulations!

Congratulations! You have successfully performed sentiment analysis on Google Docs text as well as analyzed syntax and parts of speech by calling the Natural Language API.

Analyze Sentiment with Natural Language API badge

Google Cloud training and certification

...helps you make the most of Google Cloud technologies. Our classes include technical skills and best practices to help you get up to speed quickly and continue your learning journey. We offer fundamental to advanced level training, with on-demand, live, and virtual options to suit your busy schedule. Certifications help you validate and prove your skill and expertise in Google Cloud technologies.

Manual Last Updated July 17, 2024

Lab Last Tested July 17, 2024

Copyright 2025 Google LLC. All rights reserved. Google and the Google logo are trademarks of Google LLC. All other company and product names may be trademarks of the respective companies with which they are associated.

시작하기 전에

  1. 실습에서는 정해진 기간 동안 Google Cloud 프로젝트와 리소스를 만듭니다.
  2. 실습에는 시간 제한이 있으며 일시중지 기능이 없습니다. 실습을 종료하면 처음부터 다시 시작해야 합니다.
  3. 화면 왼쪽 상단에서 실습 시작을 클릭하여 시작합니다.

시크릿 브라우징 사용

  1. 실습에 입력한 사용자 이름비밀번호를 복사합니다.
  2. 비공개 모드에서 콘솔 열기를 클릭합니다.

콘솔에 로그인

    실습 사용자 인증 정보를 사용하여
  1. 로그인합니다. 다른 사용자 인증 정보를 사용하면 오류가 발생하거나 요금이 부과될 수 있습니다.
  2. 약관에 동의하고 리소스 복구 페이지를 건너뜁니다.
  3. 실습을 완료했거나 다시 시작하려고 하는 경우가 아니면 실습 종료를 클릭하지 마세요. 이 버튼을 클릭하면 작업 내용이 지워지고 프로젝트가 삭제됩니다.

현재 이 콘텐츠를 이용할 수 없습니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

감사합니다

이용할 수 있게 되면 이메일로 알려드리겠습니다.

한 번에 실습 1개만 가능

모든 기존 실습을 종료하고 이 실습을 시작할지 확인하세요.

시크릿 브라우징을 사용하여 실습 실행하기

이 실습을 실행하려면 시크릿 모드 또는 시크릿 브라우저 창을 사용하세요. 개인 계정과 학생 계정 간의 충돌로 개인 계정에 추가 요금이 발생하는 일을 방지해 줍니다.