#!/usr/bin/ruby # Tom Luo # tom.luo@gmail.com # 2010/08/01 # install json # sudo gem install json # Follow the instructions in the post if you have problems installing json http://oracleabc.com/b/?p=339 #$KCODE='utf' require 'pp' require 'net/http' require 'uri' require 'rubygems' require 'json' require 'cgi' def translate( string, to='zh-CN', from='en' ) # You will need to change the 'from' and 'to' arguments to your languages. url = 'http://ajax.googleapis.com/ajax/services/language/translate' # another url # http://translate.google.com/translate_a/t?client=t&text=oracle&sl=en&tl=zh-CN&pc=0&oc=1 params = { :langpair => "#{from}|#{to}", :q => string, :v => 1.0 } query = params.map{ |k,v| "#{k}=#{CGI.escape(v.to_s)}" }.join('&') resp = Net::HTTP.get_response( URI.parse( "#{url}?#{query}" ) ) json = JSON.parse( resp.body ) if json['responseStatus'] == 200 json['responseData']['translatedText'] else # return nil raise StandardError, resp['responseDetails'] end end if __FILE__ == $0 string = ARGV[0] || 'oracle' lang = ARGV[1] || 'zh-CN' # Chinese puts translate( string, lang ) end