Анализируйте тональность отзывов с помощью API естественного языка Google Cloud

Уровень владения программированием : Средний
Продолжительность : 20 минут
Тип проекта : Автоматизация с настраиваемым меню

Цели

  • Поймите, для чего предназначено это решение.
  • Разберитесь, что делают службы Apps Script в рамках данного решения.
  • Настройте свою среду.
  • Настройте скрипт.
  • Запустите скрипт.

Об этом решении

You can analyze text data, such as open-ended feedback, at scale. To perform entity and sentiment analysis from within Google Sheets, this solution uses the UrlFetch Service to connect to the Google Cloud Natural Language API .

Иллюстрация принципа работы анализа настроений.

Как это работает

The script gathers text from the spreadsheet and connects to the Google Cloud Natural Language API to analyze entities and sentiment present in the string. A pivot table summarizes the average sentiment score for each entity mentioned across all rows of text data.

Сервисы Apps Script

Данное решение использует следующие сервисы:

  • Сервис электронных таблиц : отправляет текстовые данные в API обработки естественного языка Google Cloud и помечает каждую строку как «Завершено» после анализа ее эмоциональной окраски.
  • Сервис UrlFetch : подключается к API Google Cloud Natural Language для выполнения анализа сущностей и тональности текста.

Предварительные требования

Для использования этого примера необходимы следующие условия:

  • Для работы потребуется учетная запись Google (для учетных записей Google Workspace может потребоваться подтверждение администратора).
  • Веб-браузер с доступом в интернет.

  • Проект Google Cloud с привязанным платежным аккаунтом. См. раздел « Включение выставления счетов для проекта» .

Настройте свою среду

Для использования этого решения выполните следующие шаги по настройке.

Откройте свой облачный проект в консоли Google Cloud.

Если проект Cloud, который вы собираетесь использовать в этом примере, еще не открыт, откройте его:

  1. В консоли Google Cloud перейдите на страницу «Выберите проект» .

    Выберите облачный проект

  2. Select the Google Cloud project you want to use. Or, click Create project and follow the on-screen instructions. If you create a Google Cloud project, you might need to turn on billing for the project .

Включите API обработки естественного языка Google Cloud.

This solution connects to the Google Cloud Natural Language API. Before using Google APIs, you need to turn them on in a Google Cloud project. You can turn on one or more APIs in a single Google Cloud project.

  • В своем облачном проекте включите Google Cloud Natural Language API.

    Включите API

This solution requires a Cloud project with a configured consent screen. Configuring the OAuth consent screen defines what Google displays to users and registers your app so that you can publish it later.

  1. В консоли Google Cloud перейдите в >Google Auth platform > Брендинг .

    Перейти к разделу «Брендинг»

  2. Если вы уже настроили Google Auth platformВы можете настроить следующие параметры экрана согласия OAuth в разделах «Брендинг» , «Аудитория» и «Доступ к данным» . Если вы видите сообщение, в котором говорится... Google Auth platform Если конфигурация еще не выполнена , нажмите «Начать» :
    1. В разделе «Информация о приложении» , в поле «Название приложения» , введите название для приложения.
    2. В разделе «Электронная почта службы поддержки пользователей» выберите адрес электронной почты, по которому пользователи смогут связаться с вами, если у них возникнут вопросы относительно их согласия.
    3. Нажмите «Далее» .
    4. В разделе «Аудитория» выберите «Внутренняя» .
    5. Нажмите «Далее» .
    6. В поле «Контактная информация» укажите адрес электронной почты , на который вы сможете получать уведомления об изменениях в вашем проекте.
    7. Нажмите «Далее» .
    8. В разделе «Завершить» ознакомьтесь с Политикой использования пользовательских данных сервисов Google API и, если вы согласны, выберите «Я согласен с Политикой использования пользовательских данных сервисов Google API» .
    9. Нажмите «Продолжить» .
    10. Нажмите «Создать» .
  3. For now, you can skip adding scopes. In the future, when you create an app for use outside of your Google Workspace organization, you must change the User type to External . Then add the authorization scopes that your app requires. To learn more, see the full Configure OAuth consent guide.

Получите ключ API для Google Cloud Natural Language API.

  1. Перейдите в консоль Google Cloud . Убедитесь, что ваш проект с включенной функцией выставления счетов открыт.
  2. В консоли Google Cloud перейдите в > API и сервисы > Учетные данные .

    Перейдите в раздел «Учетные данные».

  3. Нажмите «Создать учетные данные» > «Ключ API» .

  4. Запишите свой API-ключ для использования на следующем шаге.

Настройте скрипт

Выполните следующие шаги для настройки скрипта.

Создайте проект Apps Script.

  1. Нажмите на следующую кнопку, чтобы создать копию электронной таблицы с примером анализа настроений при сборе отзывов . Проект Apps Script для этого решения прикреплен к электронной таблице.

    Сделать копию

  2. Нажмите «Расширения» > «Скрипты приложений» .

  3. В файле скрипта обновите следующую переменную, указав свой API-ключ:

    const myApiKey = 'YOUR_API_KEY'; // Replace with your API key.

  4. Нажмите «Сохранить». Кнопка «Сохранить проект» в редакторе .

Добавить текстовые данные

  1. Вернитесь к электронной таблице.
  2. Add text data to the id and comments columns. You can use sample vacation property reviews from Kaggle or use your own data. You can add more columns if needed, but to run successfully, the script must have data in the id and comments columns.

Запустите скрипт

  1. В верхней части электронной таблицы нажмите «Инструменты анализа настроения» > «Пометить объекты и настроение» . Возможно, потребуется обновить страницу, чтобы появилось это пользовательское меню.
  2. При появлении запроса авторизуйте скрипт. <<../_snippets/oauth.md>>
  3. Нажмите «Инструменты анализа настроения» > «Снова отметить объекты и отметьте их настроение» .
  4. После завершения выполнения скрипта переключитесь на лист «Сводная таблица» , чтобы увидеть результаты.

Просмотрите код

Чтобы просмотреть код Apps Script для этого решения, нажмите «Просмотреть исходный код» :

Просмотреть исходный код

Code.gs

solutions/automations/feedback-sentiment-analysis/code.js
// To learn how to use this script, refer to the documentation:
// https://developers.google.com/apps-script/samples/automations/feedback-sentiment-analysis

/*
Copyright 2022 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Sets API key for accessing Cloud Natural Language API.
const myApiKey = "YOUR_API_KEY"; // Replace with your API key.

// Matches column names in Review Data sheet to variables.
const COLUMN_NAME = {
  COMMENTS: "comments",
  ENTITY: "entity_sentiment",
  ID: "id",
};

/**
 * Creates a Demo menu in Google Spreadsheets.
 */
function onOpen() {
  SpreadsheetApp.getUi()
    .createMenu("Sentiment Tools")
    .addItem("Mark entities and sentiment", "markEntitySentiment")
    .addToUi();
}

/**
 * Analyzes entities and sentiment for each comment in
 * Review Data sheet and copies results into the
 * Entity Sentiment Data sheet.
 */
function markEntitySentiment() {
  // Sets variables for "Review Data" sheet
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const dataSheet = ss.getSheetByName("Review Data");
  const rows = dataSheet.getDataRange();
  const numRows = rows.getNumRows();
  const values = rows.getValues();
  const headerRow = values[0];

  // Checks to see if "Entity Sentiment Data" sheet is present, and
  // if not, creates a new sheet and sets the header row.
  const entitySheet = ss.getSheetByName("Entity Sentiment Data");
  if (entitySheet == null) {
    ss.insertSheet("Entity Sentiment Data");
    const entitySheet = ss.getSheetByName("Entity Sentiment Data");
    const esHeaderRange = entitySheet.getRange(1, 1, 1, 6);
    const esHeader = [
      [
        "Review ID",
        "Entity",
        "Salience",
        "Sentiment Score",
        "Sentiment Magnitude",
        "Number of mentions",
      ],
    ];
    esHeaderRange.setValues(esHeader);
  }

  // Finds the column index for comments, language_detected,
  // and comments_english columns.
  const textColumnIdx = headerRow.indexOf(COLUMN_NAME.COMMENTS);
  const entityColumnIdx = headerRow.indexOf(COLUMN_NAME.ENTITY);
  const idColumnIdx = headerRow.indexOf(COLUMN_NAME.ID);
  if (entityColumnIdx === -1) {
    Browser.msgBox(
      `Error: Could not find the column named ${COLUMN_NAME.ENTITY}. Please create an empty column with header "entity_sentiment" on the Review Data tab.`,
    );
    return; // bail
  }

  ss.toast("Analyzing entities and sentiment...");
  for (let i = 0; i < numRows; ++i) {
    const value = values[i];
    const commentEnCellVal = value[textColumnIdx];
    const entityCellVal = value[entityColumnIdx];
    const reviewId = value[idColumnIdx];

    // Calls retrieveEntitySentiment function for each row that has a comment
    // and also an empty entity_sentiment cell value.
    if (commentEnCellVal && !entityCellVal) {
      const nlData = retrieveEntitySentiment(commentEnCellVal);
      // Pastes each entity and sentiment score into Entity Sentiment Data sheet.
      const newValues = [];
      for (let entity in nlData.entities) {
        entity = nlData.entities[entity];
        const row = [
          reviewId,
          entity.name,
          entity.salience,
          entity.sentiment.score,
          entity.sentiment.magnitude,
          entity.mentions.length,
        ];
        newValues.push(row);
      }
      if (newValues.length) {
        entitySheet
          .getRange(
            entitySheet.getLastRow() + 1,
            1,
            newValues.length,
            newValues[0].length,
          )
          .setValues(newValues);
      }
      // Pastes "complete" into entity_sentiment column to denote completion of NL API call.
      dataSheet.getRange(i + 1, entityColumnIdx + 1).setValue("complete");
    }
  }
}

/**
 * Calls the Cloud Natural Language API with a string of text to analyze
 * entities and sentiment present in the string.
 * @param {String} the string for entity sentiment analysis
 * @return {Object} the entities and related sentiment present in the string
 */
function retrieveEntitySentiment(line) {
  const apiKey = myApiKey;
  const apiEndpoint = `https://language.googleapis.com/v1/documents:analyzeEntitySentiment?key=${apiKey}`;
  // Creates a JSON request, with text string, language, type and encoding
  const nlData = {
    document: {
      language: "en-us",
      type: "PLAIN_TEXT",
      content: line,
    },
    encodingType: "UTF8",
  };
  // Packages all of the options and the data together for the API call.
  const nlOptions = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(nlData),
  };
  // Makes the API call.
  const response = UrlFetchApp.fetch(apiEndpoint, nlOptions);
  return JSON.parse(response);
}

Авторы

Данный пример поддерживается компанией Google при содействии экспертов-разработчиков Google.

Следующие шаги