How to build a Sentiment Analysis Chatbot using Python?

Introduction

In this article, we will explore the creation of a simple Sentiment Analysis Chatbot using Python and the Tkinter GUI library. Sentiment analysis involves determining the sentiment (positive, negative, or neutral) expressed in a piece of text. Our chatbot will leverage the TextBlob library for sentiment analysis and Tkinter for the graphical user interface.

Setting Up the Environment

Before we dive into the code, it's essential to set up the necessary libraries. We'll be using TextBlob for sentiment analysis, so make sure to install it along with Tkinter. Additionally, we'll handle any dependencies related to tokenization and corpora for TextBlob.

pip install textblob
pip install tk

Analyzing Sentiment with TextBlob

Our sentiment analysis chatbot relies on the TextBlob library to assess the sentiment of the user's input. The analyze_sentiment function takes a text input, analyzes its sentiment, and returns the sentiment label, polarity, subjectivity, and the TextBlob analysis object.

from textblob import TextBlob

def analyze_sentiment(text):
    analysis = TextBlob(text)
    polarity, subjectivity = analysis.sentiment.polarity, analysis.sentiment.subjectivity
    sentiment = 'Positive' if polarity > 0 else 'Negative' if polarity < 0 else 'Neutral'
    return sentiment, polarity, subjectivity, analysis

Creating the Tkinter GUI

The graphical user interface is developed using Tkinter, the standard GUI toolkit for Python. We have a simple layout with an entry field for user input, buttons to trigger actions, and a text area to display the sentiment analysis results.

from tkinter import Tk, Label, Entry, Button, Text, Scrollbar, END, Frame, ttk
import nltk

# ... (code for setting up nltk)

class ChatbotApp:
    def __init__(self, master):
        # ... (code for initializing Tkinter components)

    def analyze_text(self):
        user_input = self.entry.get()
        sentiment, polarity, subjectivity, analysis = self.analyze_sentiment(user_input)
        explanation = self.generate_explanation(sentiment, polarity, subjectivity)
        output_message = f"Sentiment: {sentiment}\nPolarity: {polarity:.2f}\nSubjectivity: {subjectivity:.2f}\n\nExplanation: {explanation}"

        self.display_analysis_result(output_message)
        self.entry.delete(0, 'end')

    def reset_text(self):
        # ... (code for resetting text)

    def analyze_sentiment(self, text):
        # ... (code for sentiment analysis)

    def generate_explanation(self, sentiment, polarity, subjectivity):
        # ... (code for generating explanation)

Adding Animation Effects

To enhance the user experience, we can incorporate simple animation effects, such as a fade-in effect when displaying sentiment analysis results. This is achieved by adjusting the alpha (transparency) of the Text widget.

class ChatbotApp:
    def fade_in(self, widget, alpha):
        widget.attributes("-alpha", alpha)
        alpha += 0.1
        if alpha <= 1.0:
            self.master.after(50, self.fade_in, widget, alpha)

    def display_analysis_result(self, output_message):
        self.output_text.config(state='normal')
        self.output_text.delete(1.0, END)
        self.output_text.insert(END, output_message + '\n\n')
        self.output_text.config(state='disabled')

        # Fade-in animation
        self.master.after(50, self.fade_in, self.output_text, 0.0)

FullCode

from tkinter import Tk, Label, Entry, Button, Text, Scrollbar, END, Frame, ttk
from textblob import TextBlob
import nltk

try:
    nltk.data.find('tokenizers/punkt')
except LookupError:
    nltk.download('punkt')

try:
    from textblob.download_corpora import main
    main()
except nltk.exceptions.ContentRetrievalError:
    print("Error downloading corpora. Please check your internet connection.")

class ChatbotApp:
    def __init__(self, master):
        self.master = master
        master.title("Sentiment Analysis Chatbot")

        self.frame = Frame(master, padx=20, pady=20)
        self.frame.pack()

        self.label = ttk.Label(self.frame, text="Enter text:")
        self.label.grid(row=0, column=0, sticky='w')

        self.entry = ttk.Entry(self.frame, width=40)
        self.entry.grid(row=1, column=0, padx=5, pady=5)

        self.button = ttk.Button(self.frame, text="Analyze", command=self.analyze_text)
        self.button.grid(row=2, column=0, pady=10)

        self.reset_button = ttk.Button(self.frame, text="Reset", command=self.reset_text)
        self.reset_button.grid(row=2, column=1, padx=5)

        self.output_text = Text(self.frame, wrap='word', height=10, width=50, state='disabled')
        self.output_text.grid(row=3, column=0, columnspan=2, padx=5, pady=5)

        self.scrollbar = Scrollbar(self.frame, command=self.output_text.yview)
        self.scrollbar.grid(row=3, column=2, sticky='ns')

        self.output_text.config(yscrollcommand=self.scrollbar.set)

    def fade_in(self, widget, alpha):
        widget.attributes("-alpha", alpha)
        alpha += 0.1
        if alpha <= 1.0:
            self.master.after(50, self.fade_in, widget, alpha)

    def display_analysis_result(self, output_message):
        self.output_text.config(state='normal')
        self.output_text.delete(1.0, END)
        self.output_text.insert(END, output_message + '\n\n')
        self.output_text.config(state='disabled')

        # Fade-in animation
        self.master.after(50, self.fade_in, self.output_text, 0.0)

    def analyze_text(self):
        user_input = self.entry.get()

        sentiment, polarity, subjectivity, analysis = self.analyze_sentiment(user_input)
        explanation = self.generate_explanation(sentiment, polarity, subjectivity)
        output_message = f"Sentiment: {sentiment}\nPolarity: {polarity:.2f}\nSubjectivity: {subjectivity:.2f}\n\nExplanation: {explanation}"

        self.display_analysis_result(output_message)
        self.entry.delete(0, 'end')

    def reset_text(self):
        self.entry.delete(0, 'end')
        self.output_text.config(state='normal')
        self.output_text.delete(1.0, END)
        self.output_text.config(state='disabled')

    def analyze_sentiment(self, text):
        analysis = TextBlob(text)
        polarity, subjectivity = analysis.sentiment.polarity, analysis.sentiment.subjectivity
        sentiment = 'Positive' if polarity > 0 else 'Negative' if polarity < 0 else 'Neutral'
        return sentiment, polarity, subjectivity, analysis

    def generate_explanation(self, sentiment, polarity, subjectivity):
        explanation = f"The sentiment of the text is {sentiment.lower()}. "
        explanation += (
            f"It generally expresses a {'positive' if sentiment == 'Positive' else 'negative' if sentiment == 'Negative' else 'neutral'} opinion or emotion. "
            f"The polarity score is {polarity:.2f}, where a higher value indicates a stronger sentiment. "
            f"The subjectivity score is {subjectivity:.2f}, where a higher value indicates more subjective content."
        )
        return explanation

if __name__ == "__main__":
    root = Tk()
    app = ChatbotApp(root)
    root.mainloop()

Output

Sentiment Analysis Chatbot

Conclusion

In this article, we explored the development of a Sentiment Analysis Chatbot using Python and Tkinter. By combining the TextBlob library for sentiment analysis and Tkinter for the graphical interface, we created a simple yet effective tool. Additionally, we added a subtle animation effect to enhance the visual appeal of our chatbot.

This project serves as a foundation that can be expanded and customized for more advanced natural language processing tasks or integrated into larger applications. Feel free to experiment with additional features, such as incorporating machine learning models for sentiment analysis or expanding the chatbot's capabilities. Happy coding!


Similar Articles