Home  >  Article  >  Backend Development  >  Example of how to implement command line Youdao dictionary using python

Example of how to implement command line Youdao dictionary using python

高洛峰
高洛峰Original
2017-02-04 15:05:581393browse

Preface

Since I have been using the Linux system, the support for dictionaries is particularly poor. For me, a poor English speaker, I always get stuck when reading English documents. I was used to using Youdao Dictionary before. , I feel very good. Although there is a web version, it is not supported for the English web pages of the entire site. Simply implement one yourself, a small tool written in Python to implement Youdao dictionary. The idea is also very simple. Just call Youdao's API directly and parse the returned json.

Only python native libraries are used, supporting python2 and python3.

Sample code

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
# API key:273646050
# keyfrom:11pegasus11
 
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'
 
 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('无法翻译')
 
 except:
 print('翻译出错,请输入合法单词')
 
 
def main():
 try:
 s = sys.argv[1]
 except IndexError:
 s = 'python'
 parse(fetch(s))
 
 
if __name__ == '__main__':
 main()

Use

to paste the above code and name it Modify the name mv youdao.py youdao for youdao.py

, and then add executable permissions chmod a+x youdao

and copy it to /usr/local/bin. cp youdao /usr/local/bin

When using, use the word to be translated as the first command line parameter, and enclose the sentence in quotation marks.

Example of how to implement command line Youdao dictionary using python

Summary

The above is the entire content of this article. I hope the content of this article can bring some help to everyone's study or work. If you have any questions, you can leave a message to communicate.

For more examples of how to use python to implement command line Youdao dictionary, please pay attention to the PHP Chinese website for related articles!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn