Created
March 19, 2017 17:15
-
-
Save illucent/02e92529190473f1999adec881799ecd to your computer and use it in GitHub Desktop.
python youdao-dict-api
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/bash | |
word="$(xsel -o)" | |
result=$(youdao "$word") | |
notify-send --icon=info "$word" "$result" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding:utf-8 -*- | |
import json | |
import sys | |
try: # py3 | |
from urllib.parse import urlparse, quote, urlencode, unquote | |
from urllib.request import urlopen | |
except: # py2 | |
from urllib import urlencode, quote, unquote | |
from urllib2 import urlopen | |
def fetch(query_str=''): | |
query_str = query_str.strip("'").strip('"').strip() | |
if not query_str: | |
query_str = 'python' | |
query = { | |
'q': query_str | |
} | |
url = 'http://fanyi.youdao.com/openapi.do?keyfrom=yqjwsj&key=723206276&type=data&doctype=json&version=1.1&' + urlencode(query) | |
response = urlopen(url, timeout=3) | |
html = response.read().decode('utf-8') | |
return html | |
def parse(html): | |
d = json.loads(html) | |
try: | |
if d.get('errorCode') == 0: | |
translation = d.get('translation') | |
for i in translation: | |
print i.encode('utf-8') | |
if d.get('basic').get('explains'): | |
explains = d.get('basic').get('explains') | |
for i in explains: | |
print i.encode('utf-8') | |
if d.get('web'): | |
for i in d.get('web'): | |
for j in i.get('value'): | |
print j.encode('utf-8'), | |
else: | |
print('can\'t translate') | |
except: | |
print('no dict explains') | |
def main(): | |
try: | |
s = sys.argv[1] | |
except IndexError: | |
s = 'python' | |
parse(fetch(s)) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment