import urllib2,sys, json
import sys, subprocess, urllib, time

urbandictionary = 'http://www.urbandictionary.com/iphone/search/define?term='
 
def getSpeech(phrase):
    googleAPIurl = "http://translate.google.com/translate_tts?tl=en&"
    param = {'q': phrase}
    data = urllib.urlencode(param)
    googleAPIurl += data # Combine the data from the Google API
    return googleAPIurl
 
def raspberryTalk(text): # This will call mplayer and will play the sound
    subprocess.call(["mplayer",getSpeech(text)], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    
###this code section from pastebin http://pastebin.com/fcPW6m3Z ###
def search_urbandictionary(url):
  r = urllib2.urlopen(url)
  if ( r ):
    data = json.loads(r.read())
    if ( len(data['list']) > 1 ):
      data['list'] = data['list'][:2]  # only print 3 results
      for i in range(len(data['list'])):
        word = data['list'][i][u'word']
        definition = data['list'][i][u'definition']
        example = data['list'][i][u'example']
        permalink = data['list'][i][u'permalink']

        print(word + ': ' + definition),
        test = word + ': ' + definition
        print test
        raspberryTalk(test)
        print('example: ' + example),
        print('link: ' + permalink)
    else:
      print 'Word not found.'
  else:
    print 'Error connecting to UrbanDictionary.com'

raspberryTalk("Hello from the Raspberry Pi Dictionary")
   
def searching():
  your_word = raw_input("Please enter your word ")
  print " "
  search_urbandictionary(urbandictionary+your_word)
  print " "
  searching()

searching()
  
  
