Last active
August 29, 2015 14:23
-
-
Save martinandert/648890b7293f5098d407 to your computer and use it in GitHub Desktop.
Translator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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? |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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