Last active
May 11, 2017 14:59
-
-
Save porqz/58a6343f10b47cb039ef707d2ca1557e to your computer and use it in GitHub Desktop.
Yandex.Slovari and Yandex.Translate API using example
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
# encoding: UTF-8 | |
require "open-uri" | |
require "json" | |
module YandexSlovari | |
module YAPI | |
SERVICES = { | |
dictionary: { | |
key: "dict.1.1.20131227T001632Z.a3ba684c7c085e07.39c782aa6612c12f8cb2fc843564890212d60b5f", | |
url: "https://dictionary.yandex.net/api/v1/dicservice.json" | |
}, | |
predictor: { | |
key: "pdct.1.1.20131227T002741Z.f2e29ba16bbd0f0e.a6dd4d999bb6cdb990e96c5e82a09542574fd97e", | |
url: "https://predictor.yandex.net/api/v1/predict.json" | |
}, | |
translate: { | |
key: "trnsl.1.1.20131227T002801Z.8bac13124270704f.15ce12029a519d0701a9e15a5ab9a713f07bc25e", | |
url: "https://translate.yandex.net/api/v1.5/tr.json" | |
} | |
} | |
def self.send_query service_name, method_name, params = {} | |
begin | |
params.merge!({ key: SERVICES[service_name.to_sym][:key]}) | |
uri = URI.parse(SERVICES[service_name.to_sym][:url]) | |
uri.path = uri.path + "/" + method_name | |
uri.query = params.collect{ |key, value| "#{key.to_s}=#{URI.encode_www_form_component(value)}" }.join("&") | |
uri.read | |
rescue Exception => error_message | |
puts error_message | |
end | |
end | |
end | |
LANGS = ["ru", "en"] | |
def self.language_of text | |
JSON.parse(YAPI.send_query "translate", "detect", { text: text }).fetch("lang") | |
end | |
def self.suggestions_for text, max_suggestions_count = 50 | |
JSON.parse(YAPI.send_query "predictor", "complete", { q: text, lang: self.language_of(text), limit: max_suggestions_count }).fetch("text") | |
end | |
def self.translate text, to_language = "ru" | |
from_language = self.language_of text | |
lang_param = | |
if to_language != from_language | |
from_language + "-" + to_language | |
else | |
to_language | |
end | |
translation = JSON.parse(YAPI.send_query "translate", "translate", { text: text, lang: lang_param, format: "text" }).fetch("text") | |
translation | |
end | |
def self.lookup text, to_language = "ru" | |
from_language = self.language_of text | |
lang_param = from_language + "-" + to_language | |
JSON.parse(YAPI.send_query "dictionary", "lookup", { text: text, lang: lang_param, ui: "ru" }) | |
end | |
end | |
puts(YandexSlovari.translate "слово", "en") # => the word | |
puts(YandexSlovari.translate "word", "ru") # => слово | |
puts(YandexSlovari.translate "слово") # => слово | |
puts(YandexSlovari.translate "word") # => слово | |
puts(YandexSlovari.language_of "слово") # => ru |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment