命令行调用google翻译的ruby脚本

清华大佬耗费三个月吐血整理的几百G的资源,免费分享!....>>>

require 'uri'
require 'open-uri'
require 'iconv'

CN_re = /(?:\xe4[\xb8-\xbf][\x80-\xbf]|[\xe5-\xe8][\x80-\xbf][\x80-\xbf]|\xe9[\x80-\xbd][\x80-\xbf]|\xe9\xbe[\x80-\xa5])+/n unless defined? CN_re

class String
  def en2zh
    return self if self.force_encoding("ASCII-8BIT") =~ CN_re #有中文
    flg = 'auto%7czh-CN'
    g_tr(self,flg)
  end
  def zh2en
    return self if self.force_encoding("ASCII-8BIT") !~ CN_re #无中文
    flg = 'zh-CN%7cen'
    g_tr(self,flg)
  end
  if RUBY_VERSION < '1.9' 
    def force_encoding(s)
      self
    end
  end
  def utf8_to_gb
    Iconv.conv("GB18030//IGNORE","UTF-8//IGNORE",self).to_s
  end
  alias togb utf8_to_gb
end

#google 全文翻译,参数可以是中文,也可以是英文.
def g_tr(word,flg)
  word = URI.escape(word)
  url = "http://translate.google.com/translate_a/t?client=firefox-a&text=#{word}&langpair=#{flg}&ie=UTF-8&oe=UTF-8"
  uri = URI.parse(url)
  uri.open(
   'Accept'=>'image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, */*',
   'Accept'=>'text/html',
   'Referer'=> URI.escape(url)
   ){ |f|
      return f.read.match(/"trans":"(.*?)","/)[1]
  }
end

#使用方法:
puts 'show me the money'.en2zh
#puts 'show me the money'.en2zh.togb #windows 平台乱码转换
puts '可以整句翻译。'.zh2en

# wget -qO- http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1\n/';