1 问题
Google Chrome浏览器可以集成Google Translator插件,实现浏览器页面文字的翻译,但是除了浏览器,PDF、LibreOffice等软件上面的文字也经常需要翻译。
Ubuntu上可以使用有道词典,但是兼容性不太好,这里说明另外一种方法
2 安装
运行以下命令,安装所需软件:
$ sudo apt-get update
$ sudo apt-get install libnotify-bin wget xsel
-
libnotify-bin: 用于发送desktop notifications -
wget: 调用Google Translator接口,获取翻译结果 -
xsel: 获取当前highlighted的text
3 脚本
在$PATH下创建名为notitrans的脚本,赋予执行权限chmod +x notitrans,内容如下:
#!/usr/bin/env bash
notify-send --icon=info "$(xsel -o)" "$(wget -U "Mozilla/5.0" -qO - "http://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=zh&dt=t&q=$(xsel -o | sed "s/[\"'<>]//g")" | sed "s/,,,0]],,.*//g" | awk -F'"' '{print $2, $6}')"
该脚本主要做了以下几件事:
-
xsel获取当前highlighted的text - 调用Google翻译接口,获取
highlighted的text对应的翻译结果 - 把翻译结果以
notification形式发送到Desktop
上述tl=zh指明翻译的目标语言是中文,其他的有en for English,ru for Russian,fr for french
4 快捷键
设置一个快捷键shortcut,运行notitrans命令,达到按快捷键就翻译的效果
如下路径设置:
System Settings > Keyboard > Shortcuts > Custom Shortcuts
最终的效果图如下:
5 参考
http://www.webupd8.org/2016/03/translate-any-text-you-select-on-your.html
https://www.faqforge.com/linux/distributions/ubuntu/create-custom-keyboard-shortcut-ubuntu-16-04/
http://forum.ubuntu.com.cn/viewtopic.php?f=21&t=296308