Skip to content

Instantly share code, notes, and snippets.

@AO8
Created October 30, 2019 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AO8/55e486146fb51beb50f90657c7cffbf1 to your computer and use it in GitHub Desktop.
Save AO8/55e486146fb51beb50f90657c7cffbf1 to your computer and use it in GitHub Desktop.
This tiny Python app, powered by TextBlob, quickly measures the polarity and subjectiviy of a piece of text.
# This Python program quickly measures the polarity and subjectivity of a piece of text.
from time import sleep
from textblob import TextBlob
def print_header():
print("*"*67)
print("PYTHON SENTIMENT TESTER (Powered by TextBlob)")
print()
print("POLARITY:")
print()
print("-1.0 means a negative statement and 1.0 means a positive statement.\n")
print("SUBJECTIVITY:")
print()
print("0.0 is very objective and 1.0 is very subjective.\n")
print("*"*67)
def run_event_loop():
while True:
print()
text = input("Type or paste in a message below. There is no character limit. Press <enter> when finished.\n\n")
blob = create_blob(text)
display_results(blob)
sleep(5)
response = input("Would you like to analyze another piece of text? y or n\n\n").lower()
if response != "y":
print("Have a nice day!")
break
def create_blob(text):
"""Convert a string to a TextBlob object"""
return TextBlob(text)
def get_polarity(blob):
"""Rates the polarity of a text, where -1.0 means a negative statement
and 1.0 means a positive statement."""
if blob.polarity > 0:
polarity = "positive"
elif blob.polarity < 0:
polarity = "negative"
else:
polarity = "neutral"
return polarity
def get_subjectivity(blob):
"""Rates the subjectivity of a text, where 0.0 is very objective and
1.0 is very subjective."""
if blob.subjectivity > 0.5:
subjectivity = "subjective"
elif blob.subjectivity == 0.5:
subjectivity = "neutral"
elif blob.subjectivity < 0.5:
subjectivity = "objective"
return subjectivity
def display_results(blob):
"""Displays polarity and subjectivity for the text user supplied."""
print()
print("Calculating, one sec...")
sleep(2)
print("Almost done...")
sleep(2)
print("Presto!\n""")
print(f"Text Polarity: {get_polarity(blob)} ({round(blob.polarity, 2)})")
print(f"Text Subjectivity: {get_subjectivity(blob)} ({round(blob.subjectivity, 2)})")
print()
if __name__ == "__main__":
print_header()
run_event_loop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment