平時查的少,裝個翻譯軟件麻煩。以前用的是火狐的翻譯腳本,但腳本開啓後要刷新頁面;一直開啓的話,選中文字就會彈框,藍廋。
這段時間開始用 albert launcher,支持 qt 和 python 擴展,自帶 Google translator 插件。能夠改爲國內的翻譯服務。python
國內可用的翻譯服務很多:有道、金山詞霸、百度、必應、海詞、搜狗等。git
文檔:有道智雲,albert doc
可參考的插件:https://github.com/albertlauncher/python
官方demo:https://github.com/albertlauncher/python/tree/master/ApiTestgithub
# -*- coding: utf-8 -*- """Translate text using Youdao Translate API. Usage: tr <text> Example: tr hello Check available languages here: http://ai.youdao.com/docs/doc-trans-api.s#p05 """ from albertv0 import * import json import urllib.request import urllib.parse import hashlib import locale __iid__ = "PythonInterface/v0.1" __prettyname__ = "Youdao Translate" __version__ = "1.0" __trigger__ = "tr " # 觸發命令 __author__ = "jack" __dependencies__ = [] ua = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.62 Safari/537.36" urltmpl = "http://openapi.youdao.com/api?appKey={}&q={}&from=auto&to={}&salt={}&sign={}" iconPath = iconLookup('config-language') # 自定義圖標 if not iconPath: iconPath = ":python_module" # 根據 Linux 的 locale 設置自動獲取目標語言 langSupported = dict.fromkeys(('zh', 'en', 'es', 'fr', 'ko', 'ja', 'ru', 'pt')) toLang = locale.getdefaultlocale() if toLang: toLang = toLang[0].split('_')[0] # cat /etc/locale.gen if not toLang in langSupported: toLang = 'en' def getUrl(src, dst, txt): ''' 按有道的格式生成請求地址。src爲源語言,dst爲目標語言 ''' appKey = '您的應用ID' # 註冊智雲後得到 secretKey = '您的key' salt = '123456' sign = appKey + txt + salt + secretKey m1 = hashlib.md5() m1.update(sign.encode(encoding='utf-8')) sign = m1.hexdigest() q = urllib.parse.quote_plus(txt) url = urltmpl.format(appKey, q, dst, salt, sign) return url def handleQuery(query): if query.isTriggered: def getItem(text, subtext=''): # 顯示的項 item = Item( id=__prettyname__, icon=iconPath, completion=query.rawString, text=text, subtext=subtext ) item.addAction(ClipAction("Copy translation to clipboard", text)) # 項支持的操做 return item txt = query.string.strip() if txt: url = getUrl('auto', toLang, txt) req = urllib.request.Request(url, headers={'User-Agent': ua}) with urllib.request.urlopen(req) as response: items = [] # 待返回的列表 data = json.load(response) fromTo = data['l'] if 'basic' in data: if 'phonetic' in data['basic']: # 讀音 items.append(getItem('/' + data['basic']['phonetic'] + '/', fromTo)) for exp in data['basic']['explains']: # 釋義 items.append(getItem(exp, 'basic')) elif 'translation' in data: # 句子翻譯 items.append(getItem(data['translation'][0], 'translation')) if 'web' in data: # 網絡釋義 for w in data['web']: value = list(set(w['value'])) # 去重 items.append(getItem(w['key']+': '+'; '.join(value[:2]), 'web')) return items else: return getItem("Enter a translation query")
把源文件命名爲 YoudaoTranslate.py,將其拷貝到 ~/.local/share/albert/org.albert.extension.python/modules 下,而後在 albert 設置裏開啓 python 插件,而後就能夠加載這個 python 翻譯插件了。
web
在代碼裏能夠用 info(query.string)
這樣來打印調試,系統日誌裏能夠看到打印信息。json
輸入:tr hello
api