Last active
August 14, 2019 09:45
-
-
Save ruifonseca/055608778761e7d70e500cd51b15e766 to your computer and use it in GitHub Desktop.
Simple command line interface to Google Translate API
This file contains hidden or 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 | |
# Inspired by https://ctrlq.org/code/19909-google-translate-api. | |
# I usually keep these things under ~/bin... | |
require 'net/http' | |
require 'cgi' | |
require 'json' | |
# quit unless our script gets two command line arguments | |
if ARGV.empty? | |
file = File.basename(__FILE__) | |
warn 'Oops... wrong number of arguments.' | |
warn "Usage: #{file} <text-to-translate> [from:pt] [to:en]\n" | |
exit | |
end | |
st = ARGV[0] # source text | |
sl = ARGV[1] || 'pt' # source language | |
tl = ARGV[2] || 'en' # target language | |
est = CGI.escape(st) # encoded source text | |
# build http request to google's translate api | |
endpoint = 'https://translate.googleapis.com/translate_a/single' | |
params = "client=gtx&sl=#{sl}&tl=#{tl}&dt=t&q=#{est}" | |
http_request = "#{endpoint}?#{params}" | |
# parse response | |
response = Net::HTTP.get_response URI.parse(http_request) | |
translation = JSON.parse(response.body) | |
# print it | |
puts translation[0].map { |t| t[0] }.join |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment