打造純終端機翻譯工具,支援中英互譯、顯示拼音、詞性、多釋義,無需 GUI、無需 API Key,適合鍵盤流開發者。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import urllib.parse
import urllib.request
import json
import re
# 兼容 Python 2/3
try:
from urllib.parse import urlencode
from urllib.request import Request, urlopen
except ImportError:
from urllib import urlencode
from urllib2 import Request, urlopen
GOOGLE_TRANSLATE_URL = 'https://translate.google.cn/translate_a/t'
def translate(text, source='auto', target='zh-CN'):
"""呼叫 Google 翻譯非官方端點"""
params = {
'client': 't',
'text': text,
'hl': 'zh-CN',
'sl': source,
'tl': target,
'multires': '1',
'prev': 'btn',
'ssel': '0',
'tsel': '0',
}
data = urlencode(params).encode('utf-8')
req = Request(GOOGLE_TRANSLATE_URL, data=data)
req.add_header('User-Agent', 'Mozilla/5.0 (compatible; Googlebot/2.1)')
try:
with urlopen(req, timeout=10) as resp:
result = resp.read().decode('utf-8')
return parse_result(result, source, target)
except Exception as e:
return f"翻譯失敗: {e}"
def parse_result(json_text, source, target):
"""解析 Google 返回的特殊 JSON 格式"""
try:
data = json.loads(json_text)
# 結構: [[["譯文","原文",...],...], "原文語言", ...]
if not data or not data[0]:
return "無翻譯結果"
translations = data[0]
main_translation = translations[0][0] if translations[0][0] else text
phonetic = translations[0][1] if len(translations[0]) > 1 else ""
output = [f"原文: {text}", f"譯文: {main_translation}"]
if phonetic and phonetic != text:
output.append(f"拼音: {phonetic}")
# 詞性與其他釋義
if len(translations) > 1:
output.append("--- 詳細釋義 ---")
for t in translations[1:]:
if t[0] and t[0] != main_translation:
pos = t[2] if len(t) > 2 else ""
output.append(f" [{pos}] {t[0]}")
return "\n".join(output)
except Exception as e:
return f"解析失敗: {e}\n原始: {json_text[:200]}"
def main():
if len(sys.argv) < 2:
print("用法: pytran <文字> [--en2zh|--zh2en]")
print("預設: 自動偵測 → 中文")
sys.exit(1)
# 解析參數
text = ' '.join(sys.argv[1:])
source, target = 'auto', 'zh-CN'
if '--en2zh' in sys.argv:
source, target = 'en', 'zh-CN'
text = text.replace('--en2zh', '').strip()
elif '--zh2en' in sys.argv:
source, target = 'zh-CN', 'en'
text = text.replace('--zh2en', '').strip()
if not text:
print("請提供要翻譯的文字")
sys.exit(1)
print(translate(text, source, target))
if __name__ == '__main__':
main()
# 儲存為 pytran.py,賦予執行權限
chmod +x pytran.py
sudo ln -s $(pwd)/pytran.py /usr/local/bin/pytran
# 使用範例
pytran hello world
pytran "你好世界" --zh2en
pytran "machine learning" --en2zh
$ pytran extent --en2zh
原文: extent
譯文: 程度
拼音: Chéngdù
--- 詳細釋義 ---
[noun] 範圍
[noun] 幅度
[noun] 規模
chcp 65001。functools.lru_cache)。deep_translator、googletrans 庫封裝多引擎,但同樣非官方。