Last active
December 20, 2015 00:49
-
-
Save jimhj/6044402 to your computer and use it in GitHub Desktop.
Translate chars into Chinese pinyin or English.
Lies on https://github.com/flyerhzm/chinese_pinyin
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
# coding: utf-8 | |
class Translate | |
YOUDAO_HOST = "http://fanyi.youdao.com" | |
YOUDAO_QUERY_PATH = "openapi.do" | |
YOUDAO_KEY_FROM = "Paikeyun" | |
YOUDAO_KEY = "987423680" | |
def initialize(chars, opts = {}) | |
@chars = chars | |
@opts = opts | |
@opts[:pick] ||= :first | |
end | |
def to_pinyin | |
Pinyin.t(@chars, @opts) | |
end | |
def to_english(opts = nil) | |
opts ||= @opts | |
conn = Faraday.new(url: YOUDAO_HOST) { |f| f.adapter :net_http } | |
params = { | |
keyfrom: YOUDAO_KEY_FROM, | |
key: YOUDAO_KEY, | |
type: 'data', | |
doctype: "json", | |
version: '1.1', | |
q: @chars | |
} | |
translations = begin | |
resp = conn.get(YOUDAO_QUERY_PATH, params) | |
results = JSON.parse(resp.body) | |
results = results["web"].collect{ |h| h["value"] }.flatten.uniq | |
rescue => e | |
[] | |
end | |
case opts[:pick] | |
when :first, :last | |
translations.send(opts[:pick]) | |
else | |
translations | |
end | |
end | |
def self.pinyin(chars, opts = {}) | |
t = self.new(chars, opts) | |
t.to_pinyin | |
end | |
def self.english(chars, opts = {}) | |
t = self.new(chars, opts) | |
t.to_english | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment