发现了一个在线翻译的模块translators,用它可以直接在命令行上翻译内容了。
- 安装
zhangzhigangdeMacBook-Pro:mypro zhangzhigang$ pip3 install translators
- 代码如下:
#!/usr/bin/env python3
import sys
import translators as ts
# 必须提供位置参数
if len(sys.argv) < 2:
print('Usage: %s data' % sys.argv[0])
sys.exit(1)
# 将命令行上的内容拼接成字符串
data = ' '.join(sys.argv[1:])
# 本例使用搜狗翻译,还有有道、百度、谷歌等选项
try:
print(ts.sogou(data, 'auto', 'zh-CHS'))
except:
print('Network Problem')
sys.exit(2)
- 测试
zhangzhigangdeMacBook-Pro:mypro zhangzhigang$ python3 en2zh.py beautiful is better than ugly
Using China server backend.
美丽胜过丑陋
- 当然,你也可以把它搞得更像命令
zhangzhigangdeMacBook-Pro:mypro zhangzhigang$ cp en2zh.py /usr/local/bin/en2zh
zhangzhigangdeMacBook-Pro:mypro zhangzhigang$ chmod x /usr/local/bin/en2zh
zhangzhigangdeMacBook-Pro:mypro zhangzhigang$ en2zh beautiful is better than ugly
Using China server backend.
美丽胜过丑陋