Objective
As always with the Linux system, the support of the dictionary is particularly bad for my English slag people, when reading English documents have been stuck, before used to the Youdao dictionary, feel very good, although there is a web version of the website is not supported by the whole site English. Simply self-realization of a small tool based on Python to implement Youdao dictionary, the idea is very simple, direct call Youdao API, parse the return of the JSON is OK.
Only Python native libraries are used to support Python2 and Python3.
Sample code
#!/usr/bin/env python#-*-coding:utf-8-*-# API key:273646050# keyfrom:11pegasus11 import jsonimport sys try: # PY3 from Urllib.parse import urlparse, quote, UrlEncode, unquote from urllib.request import urlopenexcept: # py2 from Urllib Impor T 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 ' Print (query_str) query = {' Q ': query_str} url = ' Http://fanyi.youdao .com/openapi.do?keyfrom=11pegasus11&key=273646050&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:explains = D.get (' basic '). Get (' explains ') for I in Explains:print (i) Else:print (' cannot translate ') except:print (' translation error, please enter a valid word ') def main (): Try:s = sys.argv[1] except indexerror:s = ' python ' Parse (Fetch (s)) if __name__ = = ' __maIn__ ': Main ()
Use
Paste the above code after it is named youdao.py
Modify the name MV youdao.py Youdao, and then add the executable permission chmod a+x Youdao
Copy to/usr/local/bin. CP Youdao/usr/local/bin
Use the word to translate as the first command line argument, if the sentence is enclosed in quotation marks.
Summarize
The above is the entire content of this question, I hope that the content of this article on everyone's study or work can bring certain help, if there are questions you can message exchange.