Created
May 31, 2018 06:20
-
-
Save rominirani/9dfd1067407cddcd80cb3fbb6f659d22 to your computer and use it in GitHub Desktop.
Apps Script to invoke Google Cloud Natural Language API in Google Sheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function onOpen() { | |
var ui = SpreadsheetApp.getUi(); | |
ui.createMenu('Review Analysis Tools') | |
.addItem('Analyze Sentiment', 'analyzeSentiment') | |
.addToUi(); | |
} | |
function analyzeSentiment() { | |
var ss = SpreadsheetApp.getActiveSpreadsheet(); | |
var sheet = ss.getActiveSheet(); | |
var startRow = 2; | |
var startColumn = 1; | |
var numColumns = sheet.getLastColumn(); | |
var numRows = sheet.getLastRow(); | |
//Get the number of rows | |
var dataRange = sheet.getRange(startRow,startColumn,numRows-1,numColumns); | |
var data = dataRange.getValues(); | |
for (var i = 0; i < data.length; ++i) { | |
var row = data[i]; | |
var review = row[3]; //review column | |
//Invoke the retrieveSentiment method | |
var score = retrieveSentiment(review); | |
//Find the cell in the row (5th column) to insert the Sentiment score. | |
var range = sheet.getRange(startRow+i,numColumns); | |
//range.setValue(score); | |
if (score < 0) { | |
range.setBackground("RED"); | |
} else if (score > 0) { | |
range.setBackground("GREEN"); | |
} else { | |
range.setBackground("YELLOW"); | |
} | |
} | |
} | |
function retrieveSentiment (line) { | |
var apiKey = "YOUR_API_KEY"; | |
var apiEndpoint = 'https://language.googleapis.com/v1/documents:analyzeSentiment?key=' + apiKey; | |
var reviewData = { | |
language: 'en-us', | |
type: 'PLAIN_TEXT', | |
content: line | |
}; | |
var nlAPIData = { | |
document: reviewData, | |
encodingType: 'UTF8' | |
}; | |
var nlCallOptions = { | |
method : 'post', | |
contentType: 'application/json', | |
payload : JSON.stringify(nlAPIData) | |
} | |
var response = UrlFetchApp.fetch(apiEndpoint, nlCallOptions); | |
var data = JSON.parse(response); | |
var sentiment = 0.0; | |
if (data && data.documentSentiment && data.documentSentiment.score){ | |
sentiment = data.documentSentiment.score; | |
} | |
return sentiment; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment