平时查的少,装个翻译软件麻烦。以前用的是火狐的翻译脚本,但脚本开启后要刷新页面;一直开启的话,选中文字就会弹框,蓝廋。
这段时间开始用 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