Using IBM Watson Language Translation Services with Python

Here is a very simple example using Python of calling the IBM Watson Language Translation Service. Feel free to use and modify the code as needed. You will need an IBM Bluemix account in order to use the translation service.

# CTEC 121 Intro to Programming and Problem Solving
# Bruce Elgort / Clark College
# Using IBM Watson's Language Translator
# February 27, 2016
# Revised: May 24, 2016
# Version 1.1

import requests

def cls():
    print("\n" * 5)

def translate_text(text,source,target):
    username = 'your username'
    password = 'your password'
    watsonUrl = 'https://gateway.watsonplatform.net/language-translation/api/v2/translate?source=' + source + '&target=' + target + '&text=' + text
    try:
        r = requests.get(watsonUrl,auth=(username,password))
        #print(r)
        return r.text
    except:
        return False

def welcome():
    message = "Welcome to the IBM Watson Translator\n"
    print(message + "-" * len(message) + "\n")
    print("Have fun!\n")

def main():
    cls()
    welcome()

    data = input("Enter some text to be translated:\n")

    print()
    print("What language should I translate it to?")
    print("1) Spanish")
    print("2) Arabic")
    print("3) French")
    print("4) Portuguese")
    print()
    target = input("Select a language from the list above: ")

    if target == "1":
        target = 'es'
    elif target == "2":
        target = 'ar'
    elif target == "3":
        target = 'fr'
    elif target == "4":
        target = 'pt'

    results = translate_text(data,'en',target)
    print()
    print("Here is the text translated for you:")
    print(results)

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: