命令列控制翻譯工具,透過模擬瀏覽器請求 Google Translate (translate.google.cn) 取得翻譯結果,支援中翻英、英翻中,顯示來源詞、譯文、拼音、詞性與其他釋義。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import urllib, urllib2, sys, re
def help_info():
print("Usage: pytran {zh2en|en2zh} content")
def format_result(result, src_lang):
parts = result.split('[[')
if src_lang in ('en2zh', 'zh2en'):
first = parts[1].replace('[', '').replace(']', '').split('"')
print("源詞:", first[3])
print("結果:", first[1])
pinyin = first[7] if src_lang == 'zh2en' else first[5]
print("拼音:", pinyin)
sec = parts[2].replace('"', '').split('[')
print("詞性:", sec[0].replace(',', ''))
print("其他釋義:")
for item in ''.join(sec[1].split(']')).split(','):
print(item)
try:
mode = sys.argv[1]
text = sys.argv[2]
except IndexError:
help_info()
sys.exit(1)
if mode == 'zh2en':
data = urllib.urlencode({'client': 't', 'text': text, 'hl': 'zh-CN', 'tl': 'en', 'multires': '1', 'prev': 'btn', 'ssel': '0', 'sc': '1'})
elif mode == 'en2zh':
data = urllib.urlencode({'client': 't', 'text': text, 'hl': 'zh-CN', 'sl': 'en', 'tl': 'zh-CN', 'multires': '1', 'prev': 'btn', 'ssel': '0', 'sc': '1'})
else:
help_info()
sys.exit(1)
url = 'https://translate.google.cn/translate_a/t'
req = urllib2.Request(url, data)
req.add_header("User-Agent", "Mozilla/5.0 (compatible; Googlebot/2.1; +https://www.google.com/bot.html)")
resp = urllib2.urlopen(req)
format_result(resp.read(), mode)
resp.close()
chmod +x pytran
sudo cp pytran /usr/bin/
pytran en2zh extent
# 源詞: extent
# 結果: 程度
# 拼音: Chéngdù
# 詞性: 名詞
# 其他釋義: 程度 范圍 幅度 ...
pytran zh2en 中國
# 源詞: 中國
# 結果: China
# 拼音: Zhōngguó
# 詞性: 名詞
# 其他釋義: China
Google Cloud Translation API(付費、穩定、有 SLA)。urllib/urllib2 改為 urllib.parse/urllib.request。