Skip to content

Instantly share code, notes, and snippets.

@paractmol
Created December 24, 2012 15:35
Show Gist options
  • Save paractmol/4369670 to your computer and use it in GitHub Desktop.
Save paractmol/4369670 to your computer and use it in GitHub Desktop.
Google Translation.
# encoding: UTF-8
#
#1.9.3-p327 :013 > t = GTranslate.new "This stuff is pretty unexpected!", "pl"
#=> #<GTranslate:0x0000000195b0b8 @lang="pl", @text="This stuff is pretty unexpected!", @response=["[[[\"Ten materiał jest dość nieoczekiwanego!\",\"This stuff is pretty unexpected!\",\"\",\"\"]],,\"en\",,[[\"Ten materiał jest\",[5],1,0,802,0,3,0],[\"dość\",[6],1,0,792,3,4,0],[\"nieoczekiwanego!\",[7],1,0,726,4,6,0]],[[\"This stuff is\",5,[[\"Ten materiał jest\",802,1,0],[\"Tych rzeczy jest\",0,1,0],[\"Te rzeczy są\",0,1,0]],[[0,13]],\"This stuff is pretty unexpected!\"],[\"pretty\",6,[[\"dość\",792,1,0],[\"całkiem\",9,1,0],[\"pretty\",0,1,0],[\"śliczny\",0,1,0],[\"ładna\",0,1,0]],[[14,20]],\"\"],[\"unexpected !\",7,[[\"nieoczekiwanego!\",726,1,0]],[[21,32]],\"\"]],,,[[\"en\"]],28]"]>
#1.9.3-p327 :014 > t.parse[0]
# => ["Ten materiał jest dość nieoczekiwanego!"]
#
class GTranslate
require 'net/http'
TRANSLATE_URL = 'http://translate.google.com/translate_a/t'
attr_accessor :text, :lang, :response
def initialize(text, lang = 'en')
@response, @text, @lang = [], text, lang
translate
end
def parse
response.join.scan(/[^\\](\p{alnum}.*?)[\\"$]/i)
end
def translate
uri = URI(TRANSLATE_URL)
uri.query = URI.encode_www_form({ client: 't',
text: @text, hl: 'en',
sl: 'auto', tl: @lang,
ie: 'UTF-8', oe: 'UTF-8',
multires: 1, otf: 1,
ssel: 0, tsel: 0,
uptl: @lang, alttl: 'en',
sc: 1 })
res = Net::HTTP.get_response(uri)
@response << res.body.force_encoding(Encoding::UTF_8) if res.is_a?(Net::HTTPSuccess)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment