📜 ⬆️ ⬇️

Simple Ruby Translator

Using mechanize and hpricot wrote a class of very useful translator.

At the moment, there are 3 servers available for translating translate.meta.ua, translate.google.com and pereklad.online.ua

Code example:

def initialize(url=:meta)
Hpricot.buffer_size = 2621444

@agent = WWW::Mechanize.new
@url = url || :meta
@url = :meta unless BASE_URL.keys.include?(url)
@page = @agent.get BASE_URL[url]
end

def ru_to_ua(text)
translate(@url, :ru, :ua, text)
end

def translate(url, lang_from, lang_to, text)
self.send "translate_#{url.to_s}", text, @@default_options[url][lang_from.to_sym], @@default_options[url][lang_to.to_sym]
end

def translate_meta(text, lang_from, lang_to)
form = @page.form_with(:name => "form1")
form.field_with(:name => "SrcTxt").value = text
form.field_with(:name => "language").value = "{lang_from}-{lang_to}"
results = @agent.submit(form)
Hpricot(results.body).at('//textarea[@name="DstTxt"]').inner_text
end


Example of use:

tr = Translate.new(:online)
tr.ru_to_en("") # => example
tr.en_to_ru("see") # =>
tr.ru_to_ua("") # =>


This thing was very useful to me. For example, it was necessary to translate a column in the xsl file from Ukrainian to Russian (50,000 data). The program did it in 2-3 hours.
')
excel = WIN32OLE.new('excel.application')
excel.visible = true
excel.workbooks.open(".xlsx")
trans = Translate.new(:meta)
50000.times do |i|
if i>1
str = trans.ua_to_ru(excel.range('B' + i.to_s).value)
excel.range('C' + i.to_s).value = str
end
end


If anyone is interested, I can give all the code :)

Source: https://habr.com/ru/post/62856/


All Articles