Example of how to use the python command line youdao dictionary, python command line
Preface
Since I have been using the Linux system, it is particularly difficult to support dictionaries. For those of me who have been reading English documents, I have been stuck in shells and used a proper dictionary before, I feel very good. Although there is a web version, it is not supported for full-site English web pages. Simply implement one by yourself. The idea of implementing youdao Dictionary Based on Python is also very simple. You can directly call youdao api and parse the returned json.
Only use the python native library and support python2 and python3.
Sample Code
#! /Usr/bin/env python #-*-coding: UTF-8-*-# API key: 273646050 # keyfrom: 11pegasus11import jsonimport systry: # py3 from urllib. parse import urlparse, quote, urlencode, unquote from urllib. request import urlopenworkflow T: # py2 from urllib import urlencode, quote, unquote from urllib2 import urlopendef 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 htmldef 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 ('unable to translate ') failed T: print ('translation error, please enter valid word ') def main (): try: s = sys. argv [1] doesn t IndexError: s = 'python' parse (fetch (s) if _ name _ = '_ main _': main ()
Use
Paste the above Code and name ityoudao.py
Modify namemv youdao.py youdao
And then add the executable permission.chmod a+x youdao
Copy/usr/local/bin
.cp youdao /usr/local/bin
When used, the words to be translated are used as the first command line parameter. if the sentence is enclosed by quotation marks.
Summary
The above is all the content of this article. I hope this article will help you in your study or work. If you have any questions, you can leave a message.