This content originally appeared on Level Up Coding - Medium and was authored by Dilip Kashyap
Hi Folks,
In today’s fast-paced digital world, gathering and analyzing customer feedback is critical for improving services. Manual analysis of feedback can be slow and prone to bias. This article provides a solution that automates the process of sentiment analysis using Google Cloud Natural Language API. Customer feedback submitted through Google Forms is fetched, analyzed for sentiment (positive, neutral, or negative), and the results are automatically stored in Google Sheets.
Workflow
- Fetch feedback: Use the Google Forms API to retrieve form responses.
- Sentiment analysis: Analyze the text responses using Google Cloud’s Natural Language API.
- Store results: Output sentiment scores in Google Sheets.
Step-by-Step Code and Explanation
Step 1: Set Up Google Cloud and Google Apps Script
Before diving into the code, ensure that you have:
- A Google Cloud project with the Natural Language API enabled.
- Set up the OAuth credentials to allow the Google Apps Script to access Google Forms and Sheets.
- An active Google Form and a corresponding Google Sheet to store the results.
Step 2: Google Apps Script to Fetch Form Responses
First, we need a script to fetch responses from a Google Form. We use the Form ID to access the form responses.
function fetchFormResponses() {
const formId = 'YOUR_GOOGLE_FORM_ID'; // Replace with your Google Form ID
const form = FormApp.openById(formId);
const responses = form.getResponses();
const formData = [];
// Iterate through each response
responses.forEach(response => {
const itemResponses = response.getItemResponses();
const responseObject = {};
itemResponses.forEach(itemResponse => {
const questionTitle = itemResponse.getItem().getTitle();
const answer = itemResponse.getResponse();
responseObject[questionTitle] = answer;
});
formData.push(responseObject);
});
return formData; // Returns the form responses as an array of objects
}
Explanation:
- FormApp.openById(formId): Opens the Google Form using its ID.
- getResponses(): Retrieves all the form submissions.
- We loop through the responses, extracting both the question and the answer. This data will later be passed to the sentiment analysis function.
Step 3: Perform Sentiment Analysis with Google Cloud Natural Language API
Next, we will analyze each piece of feedback using the Google Cloud Natural Language API.
function analyzeSentiment(text) {
const apiKey = 'YOUR_GOOGLE_CLOUD_API_KEY'; // Replace with your Google Cloud API key
const url = `https://language.googleapis.com/v1/documents:analyzeSentiment?key=${apiKey}`;
const document = {
document: {
type: 'PLAIN_TEXT',
content: text
},
encodingType: 'UTF8'
};
const options = {
method: 'POST',
contentType: 'application/json',
payload: JSON.stringify(document)
};
const response = UrlFetchApp.fetch(url, options);
const sentimentResult = JSON.parse(response.getContentText());
return sentimentResult.documentSentiment;
}
Explanation:
- The function takes the feedback text as input and sends a POST request to the Google Cloud Natural Language API.
- The document type is set to PLAIN_TEXT, meaning the API will process simple text strings.
- UrlFetchApp.fetch() sends the request and retrieves the sentiment analysis result, which includes a score (ranging from -1 to 1) and magnitude (the overall strength of emotion).
Step 4: Store Results in Google Sheets
We’ll now create a function to store the sentiment results into a Google Sheet.
function storeSentimentResults(feedback, sentiment) {
const sheetId = 'YOUR_GOOGLE_SHEET_ID'; // Replace with your Google Sheet ID
const sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
const feedbackRow = [
feedback,
sentiment.score,
sentiment.magnitude,
classifySentiment(sentiment.score)
];
sheet.appendRow(feedbackRow);
}
function classifySentiment(score) {
if (score > 0.25) {
return 'Positive';
} else if (score < -0.25) {
return 'Negative';
} else {
return 'Neutral';
}
}
Explanation:
- storeSentimentResults(): Appends feedback, the sentiment score, and the sentiment classification (positive, neutral, or negative) to a Google Sheet.
- classifySentiment(): Determines if the feedback is positive, negative, or neutral based on the sentiment score.
Step 5: Combine Everything Together
Finally, we need a main function to run the entire process: fetch form responses, analyze each response’s sentiment, and store the results.
function analyzeCustomerFeedback() {
const formData = fetchFormResponses();
formData.forEach(response => {
const feedback = response['Feedback']; // Assuming "Feedback" is the question title
const sentiment = analyzeSentiment(feedback);
storeSentimentResults(feedback, sentiment);
});
}
Explanation:
- This function ties everything together by fetching responses, analyzing the sentiment of each response, and then storing the results in a Google Sheet.
Complete Code
function fetchFormResponses() {
const formId = 'YOUR_GOOGLE_FORM_ID';
const form = FormApp.openById(formId);
const responses = form.getResponses();
const formData = [];
responses.forEach(response => {
const itemResponses = response.getItemResponses();
const responseObject = {};
itemResponses.forEach(itemResponse => {
const questionTitle = itemResponse.getItem().getTitle();
const answer = itemResponse.getResponse();
responseObject[questionTitle] = answer;
});
formData.push(responseObject);
});
return formData;
}
function analyzeSentiment(text) {
const apiKey = 'YOUR_GOOGLE_CLOUD_API_KEY';
const url = `https://language.googleapis.com/v1/documents:analyzeSentiment?key=${apiKey}`;
const document = {
document: {
type: 'PLAIN_TEXT',
content: text
},
encodingType: 'UTF8'
};
const options = {
method: 'POST',
contentType: 'application/json',
payload: JSON.stringify(document)
};
const response = UrlFetchApp.fetch(url, options);
const sentimentResult = JSON.parse(response.getContentText());
return sentimentResult.documentSentiment;
}
function storeSentimentResults(feedback, sentiment) {
const sheetId = 'YOUR_GOOGLE_SHEET_ID';
const sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
const feedbackRow = [
feedback,
sentiment.score,
sentiment.magnitude,
classifySentiment(sentiment.score)
];
sheet.appendRow(feedbackRow);
}
function classifySentiment(score) {
if (score > 0.25) {
return 'Positive';
} else if (score < -0.25) {
return 'Negative';
} else {
return 'Neutral';
}
}
function analyzeCustomerFeedback() {
const formData = fetchFormResponses();
formData.forEach(response => {
const feedback = response['Feedback'];
const sentiment = analyzeSentiment(feedback);
storeSentimentResults(feedback, sentiment);
});
}
Use Cases
- Customer Support Feedback: Automatically assess the tone of customer support feedback to detect dissatisfaction and act accordingly.
- Product Reviews: Analyze product feedback to understand customer satisfaction and product performance.
- Employee Feedback: Companies can monitor internal sentiment through feedback forms for better organizational health.
- Event Feedback: After events or workshops, analyze feedback to evaluate participant satisfaction.
- Survey Results: Automatically gauge sentiment in open-ended survey questions to derive insights from qualitative data.
I hope you find this article helpful. For the latest post intimation, you may follow, subscribe, and share this with your friends. Happy learning! 💻🥳🎉
Boost your Google Workspace potential with our e-book: Google Apps Script: A Beginner’s Guide. Streamline your workflow and automate tasks today. Get your copy now!
Please feel free to contact me via email at dilipkashyap.sd@gmail.com. Thank you :)
Buy me a Coffee 🍵
AI-Driven Sentiment Analysis for Customer Feedback was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Level Up Coding - Medium and was authored by Dilip Kashyap
Dilip Kashyap | Sciencx (2024-11-12T17:51:22+00:00) AI-Driven Sentiment Analysis for Customer Feedback. Retrieved from https://www.scien.cx/2024/11/12/ai-driven-sentiment-analysis-for-customer-feedback/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.