-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathyoudao.py
More file actions
56 lines (46 loc) · 1.34 KB
/
Copy pathyoudao.py
File metadata and controls
56 lines (46 loc) · 1.34 KB
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
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import json
import sys
import requests
import locale
from urllib import urlencode
def fetch(query_str=''):
query_str = query_str.strip("'").strip('"').strip()
if not query_str:
query_str = 'python'
query = {
'q': query_str.encode("utf-8")
}
url = 'http://fanyi.youdao.com/openapi.do?keyfrom=linxianwu201&key=829523590&type=data&doctype=json&version=1.1&%s' % urlencode(
query)
req = requests.get(url)
html = req.content.decode("utf8", 'ignore')
return html
def parse(html):
try:
d = json.loads(html)
except:
print '翻译出错,请输入合法单词'
try:
print "translate:\n ---> {0}".format(d["translation"][0])
except Exception as e:
print "translate:\n ---> {no translate}"
try:
print "dict:\n",
if d.get('errorCode') == 0:
explains = d.get('basic').get('explains')
for i in explains:
print " --->%s" % i
else:
print '无法翻译'
except Exception as e:
print " --->{no dict}"
def main():
try:
s = " ".join(sys.argv[1:]).decode(sys.stdin.encoding or locale.getpreferredencoding(True))
except IndexError:
s = u'python'
parse(fetch(s))
if __name__ == '__main__':
main()