forked from dengshilong/ydd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathydd.py
103 lines (91 loc) · 3.01 KB
/
ydd.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#coding: utf-8
import os
import subprocess
import requests
import click
import six
from click_default_group import DefaultGroup
API_URL = "http://fanyi.youdao.com/openapi.do?keyfrom=ydd-dict&key=1890264650&type=data&doctype=json&version=1.1"
HISTORY_PATH = os.environ['HOME'] + "/.ydd_history.txt"
def show_basic(s):
basic = s["basic"]
phonetic = ''
if "phonetic" in basic:
if six.PY3:
phonetic = '发音 {}'.format(basic["phonetic"])
else:
phonetic = u'发音 {}'.format(basic["phonetic"])
if "us-phonetic" in basic:
if six.PY3:
phonetic += " 美式发音 {}".format(basic["us-phonetic"])
else:
phonetic += u" 美式发音 {}".format(basic["us-phonetic"])
if phonetic:
click.secho(phonetic, fg='red')
for explain in basic["explains"]:
click.secho(explain, fg='blue')
def show_web(s):
click.secho("#" * 8, fg="green")
web = s["web"]
for item in web:
if six.PY3:
click.secho("{} : {}".format(item["key"], '; '.join(item["value"])), fg='green')
else:
click.secho(u"{} : {}".format(item["key"], '; '.join(item["value"])), fg='green')
def show_result(s):
error_code = s["errorCode"]
if error_code == 0:
click.secho(' '.join(s["translation"]), fg='red')
if "basic" in s:
show_basic(s)
if "web" in s:
show_web(s)
save_history(s)
elif error_code == 20:
click.secho('too long text(要翻译的文本过长)', fg='red')
elif error_code == 30:
click.secho("can't tranlate text(无法进行有效的翻译)", fg='red')
elif error_code == 40:
click.secho("unsupport language(不支持的语言类型)", fg='red')
elif error_code == 50:
click.secho("useless api key(无效的key)", fg='red')
else:
click.secho("no result(无词典结果)", fg='red')
def get_response_json(query):
params = {"q": query}
response = requests.get(API_URL, params=params)
data = response.json()
return data
def save_history(s):
key = s["query"]
explain = ' '.join(s["translation"])
line = key + ' ' + explain + '\n'
with open(HISTORY_PATH, 'a+') as f:
if six.PY3:
f.write(line)
else:
f.write(line.encode('utf-8'))
@click.group(cls=DefaultGroup, default='translate')
def cli():
pass
@cli.command(help='query and translate words')
@click.argument('words', nargs=-1)
def translate(words):
if not words:
click.secho("enter words(请输入单词)", fg='red')
return
query = ' '.join(words)
result = get_response_json(query)
show_result(result)
@cli.command(help='show query history')
@click.option('--d', is_flag=True, help='clear history')
def history(d):
exist = os.path.exists(HISTORY_PATH)
if not exist:
return
if d:
subprocess.call("rm %s" % HISTORY_PATH, shell=True)
return
subprocess.call("cat %s" % HISTORY_PATH, shell=True)
if __name__ == '__main__':
cli()