Using IBM Watson Tone Analyzer with Python

Here is a sample Python program that you can use to analyze the tone of text using IBM’s Watson Tone Analysis service on Bluemix. To get started with Bluemix you can sign up at http://bluemix.net. Feel free to use and modify the code as needed.

# CTEC 121 Intro to Programming and Problem Solving
# Bruce Elgort / Clark College
# Using IBM Watson's Tone Analyzer to detect and interpret emotional, social, and writing cues found in text.
# February 26, 2016
# Version 1.0

import requests
import json

def analyze_tone(text):
    username = 'your username'
    password = 'your password'
    watsonUrl = 'https://gateway.watsonplatform.net/tone-analyzer-beta/api/v3/tone?version=2016-05-18'
    headers = {"content-type": "text/plain"}
    data = text
    try:
        r = requests.post(watsonUrl, auth=(username,password),headers = headers,
         data=data)
        return r.text
    except:
        return False

def welcome():
    message = "Welcome to the IBM Watson Tone Analyzer\n"
    print(message + "-" * len(message) + "\n")
    message = "How it works"
    print(message)
    message = "Perhaps a bit too aggressive in your emails? Are your blog posts a little too friendly? Tone Analyzer might be able to help. The service uses linguistic analysis to detect and interpret emotional, social, and writing cues found in text."
    print(message)
    print()
    print("Have fun!\n")

def display_results(data):
    data = json.loads(str(data))
    print(data)
    for i in data['document_tone']['tone_categories']:
        print(i['category_name'])
        print("-" * len(i['category_name']))
        for j in i['tones']:
            print(j['tone_name'].ljust(20),(str(round(j['score'] * 100,1)) + "%").rjust(10))
        print()
    print()

def main():
    welcome()
    
    data = input("Enter some text to be analyzed for tone analysis by IBM Watson (Q to quit):\n")
    if len(data) >= 1:
        if data == 'q'.lower():
            exit
        results = analyze_tone(data)
        if results != False:
            display_results(results)
            exit
        else:
            print("Something went wrong")

main()

Advertisement

Author: Bruce Elgort

You’ll find this technology professor – an award-winning instructor at Clark College – working hard to inspire and challenge his students with meaningful web development and programming experiences. With a skinny vanilla latte (no foam) in hand, Bruce loves to tinker and test the boundaries of existing and emerging technologies, to then guide hungry minds through memorable, educational journeys to showcase with passion the ever-evolving innovations of society. An industry leader, Bruce is known for co-developing Elguji’s IdeaJam software, and is recognized by IBM as an ‘IBM Champion’ for being an innovative thought leader in cloud technologies.

%d bloggers like this: