Skip to content

Instantly share code, notes, and snippets.

@martinandert

martinandert/translate

Last active Aug 29, 2015
Embed
What would you like to do?
Translator
me@home ~ $ translate
Usage: translate SOURCE_LANG TARGET_LANG TEXT...
me@home ~ $ translate de en Bank
bank
bench
seat
pew
settle
form
squab
me@home ~ $ translate en fr "Hello, Martin! How are you today?"
Bonjour, Martin ! Comment allez-vous aujourd'hui?
#!/usr/bin/env ruby
require 'json'
require 'uri'
module Translator
def translate(str, from = "de", to = "en")
query = URI.encode(str)
cmd = "curl -A 'Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0' "
cmd << "'https://translate.google.de/translate_a/single?client=t&sl=#{from}&tl=#{to}&dt=bd&dt=ex&dt=ld&dt=md&dt=qca&dt=rw&dt=rm&dt=ss&dt=t&dt=at&ie=UTF-8&oe=UTF-8&q=#{query}' "
cmd << "2> /dev/null"
result = `#{cmd}`
result = result.gsub(/,,/, ',null,').gsub(/,,/, ',null,').gsub(/\[,/, '[null,').gsub(/,\]/, ',null]')
result = JSON.parse(result)
result[1][0][1] rescue [result[0].map { |x| x[0] }.join]
end
def method_missing(method, *args, &block)
if method =~ /^([a-z]{2})_to_([a-z]{2})$/ && args.size == 1
translate args.first, $1, $2
else
super
end
end
extend self
end
if $0 == __FILE__
if ARGV.size >= 3
from, to = ARGV.shift.downcase, ARGV.shift.downcase
text = ARGV.join(" ")
puts Translator.translate(text, from, to).join("\n")
else
STDERR.puts "Usage: #{File.basename($0)} SOURCE_LANG_CODE TARGET_LANG_CODE TEXT..."
exit 1
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment