forked from FeeiCN/dict
-
Notifications
You must be signed in to change notification settings - Fork 1
/
fanyi.py
executable file
·85 lines (73 loc) · 2.64 KB
/
fanyi.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
#!/usr/bin/env python
import sys
import json
import urllib
import urllib2
"""
dict - Chinese/English Translation
@author Feei([email protected])
@date 2013.12.09
"""
class Dict:
key = '716426270'
keyFrom = 'wufeifei'
api = 'http://fanyi.youdao.com/openapi.do?keyfrom=wufeifei&key=716426270&type=data&doctype=json&version=1.1&q='
content = None
def __init__(self, argv):
if len(argv) == 1:
self.api = self.api + urllib.quote(argv[0])
self.translate()
else:
print 'ERROR'
def translate(self):
content = urllib2.urlopen(self.api).read()
self.content = json.loads(content)
self.parse()
def parse(self):
code = self.content['errorCode']
if code == 0: # Success
try:
u = self.content['basic']['us-phonetic'] # English
e = self.content['basic']['uk-phonetic']
except KeyError:
try:
c = self.content['basic']['phonetic'] # Chinese
except KeyError:
c = 'None'
u = 'None'
e = 'None'
try:
explains = self.content['basic']['explains']
except KeyError:
explains = 'None'
print '\033[1;31m################################### \033[0m'
print '\033[1;31m# \033[0m', self.content['query'], self.content['translation'][0],
if u != 'None':
print '(U:', u, 'E:', e, ')'
elif c != 'None':
print '(Pinyin:', c, ')'
else:
print
if explains != 'None':
for i in range(0, len(explains)):
print '\033[1;31m# \033[0m', explains[i]
else:
print '\033[1;31m# \033[0m Explains None'
print '\033[1;31m################################### \033[0m'
# Phrase
# for i in range(0, len(self.content['web'])):
# print self.content['web'][i]['key'], ':'
# for j in range(0, len(self.content['web'][i]['value'])):
# print self.content['web'][i]['value'][j]
elif code == 20: # Text to long
print 'WORD TO LONG'
elif code == 30: # Trans error
print 'TRANSLATE ERROR'
elif code == 40: # Don't support this language
print 'CAN\'T SUPPORT THIS LANGUAGE'
elif code == 50: # Key failed
print 'KEY FAILED'
elif code == 60: # Don't have this word
print 'DO\'T HAVE THIS WORD'
if __name__ == '__main__':
Dict(sys.argv[1:])