From 2c43963709ebe122ecd6b3200378a2f673ae2f3c Mon Sep 17 00:00:00 2001 From: NIKITA PANDEY <113332472+nikitapandeyy@users.noreply.github.com> Date: Sun, 19 Mar 2023 22:55:09 +0530 Subject: [PATCH] Update sentiment.py This version of the code uses a function calculate_sentiment() that takes the text as an input and returns the sentiment polarity value. It also includes some error handling to catch any exceptions that may occur during the sentiment analysis process. The if __name__ == "__main__": block ensures that the code only runs when this file is executed directly and not when it is imported as a module. The output is rounded to two decimal places using f-strings to improve readability. --- sentiment.py | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/sentiment.py b/sentiment.py index 801a093..b7cdb86 100644 --- a/sentiment.py +++ b/sentiment.py @@ -1,14 +1,18 @@ #pip install TextBlob #import TextBlob -from textblob import TextBlob - -text = "Python is a very good language to learn" -obj = TextBlob(text) +from textblob import TextBlob -#returns the sentiment of text -#by returning a value between -1.0 and 1.0 -sentiment = obj.sentiment.polarity +def calculate_sentiment(text): + blob = TextBlob(text) + sentiment = blob.sentiment.polarity + return sentiment -print(sentiment) +if __name__ == "__main__": + text = input("Enter the text: ") + try: + sentiment = calculate_sentiment(text) + print(f"Sentiment: {sentiment:.2f}") + except Exception as e: + print(f"Error: {e}")