Created
August 22, 2012 10:26
-
-
Save jugyo/3424202 to your computer and use it in GitHub Desktop.
Sublime Google Translate Plugin
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
# Preferences.sublime-settings | |
# | |
# { | |
# ... | |
# "google_translate_mode": "en>ja", | |
# "google_translate_api_key": "API-KEY" | |
# } | |
# | |
# Default.sublime-keymap | |
# | |
# [ | |
# ... | |
# { "keys": ["ctrl+shift+t"], "command": "google_translate" } | |
# ] | |
import sublime, sublime_plugin | |
import urllib2 | |
import json | |
import urllib | |
import HTMLParser | |
def translate(api_key, text, sourcelang, targetlang): | |
url = 'https://www.googleapis.com/language/translate/v2?key={0}&q={1}&source={2}&target={3}'.format( | |
api_key.encode('utf-8'), | |
urllib.quote(text.encode('utf-8')), | |
sourcelang.encode('utf-8'), | |
targetlang.encode('utf-8') | |
) | |
request = urllib2.Request(url) | |
response = urllib2.urlopen(request).read() | |
data = json.loads(response) | |
text = HTMLParser.HTMLParser().unescape(data['data']['translations'][0]['translatedText']) | |
return text | |
class GoogleTranslateCommand(sublime_plugin.TextCommand): | |
def run(self, edit): | |
sel = self.view.sel()[0] | |
text = self.view.substr(sel) | |
config = sublime.load_settings('Preferences.sublime-settings').get("google_translate_mode"); | |
api_key = sublime.load_settings('Preferences.sublime-settings').get("google_translate_api_key"); | |
if config is None: | |
config = 'en>ja' | |
langs = config.split('>') | |
if len(langs) != 2: | |
raise Exception, u'Erorr configuration. Value sublang requre {1}>{2}' | |
else: | |
sourcelang = langs[0] | |
targetlang = langs[1] | |
result = translate(api_key, text, sourcelang, targetlang) | |
self.view.insert(edit, sel.end(), result) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment