Skip to content

Instantly share code, notes, and snippets.

@schfkt
Last active January 3, 2016 06:09
Show Gist options
  • Save schfkt/8420435 to your computer and use it in GitHub Desktop.
Save schfkt/8420435 to your computer and use it in GitHub Desktop.
Tr
# encoding: utf-8
require 'open-uri'
require 'json'
require 'optparse'
API_KEY = "change_me" # put yandex.slovari API key here
API_URL = "https://dictionary.yandex.net/api/v1/dicservice.json/lookup?"\
"key=%s&lang=en-ru&text=%s"
options = {}
OptionParser.new do |opts|
opts.banner = "Usage: tran [options]"
opts.on("-i", "--input FILE", "Input file with words") do |v|
options[:input] = v
end
opts.on("-o", "--output FILE", "File for translations") do |v|
options[:output] = v
end
opts.on_tail("-h", "--help", "Show this message") do
puts opts
exit
end
end.parse!
required_opts = [:input, :output]
required_opts.each do |opt|
if options[opt].nil?
puts "parameter --#{opt} is required"
exit false
end
end
unless File.exist?(options[:input])
puts "Input file doesn't exist"
exit false
end
unless File.readable?(options[:input])
puts "Can't read input file"
exit false
end
words = File.open(options[:input], "r", &:readlines)
output_file = File.open(options[:output], "w")
puts "Translating..."
counter = 0
words.each_with_index do |word, index|
word.strip!
response = JSON.parse(open(API_URL % [API_KEY, word]).read)
definitions = response["def"]
definition = definitions.find { |definition| definition["ts"] }
transcription = definition["ts"] if definition
all_translations = definitions.inject([]) do |result, definition|
translation = definition["tr"].map { |tr| tr["text"] }
result << translation unless translation.empty?
result
end
if all_translations.length >= 1
translation = all_translations.first.take(2).join(", ").strip
output_file.write("#{word}\t#{translation}\t[#{transcription}]\n")
output_file.write("\n\n") if (counter + 1) % 15 == 0
counter += 1
end
end
output_file.close
puts "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment