【基础】python实现命令行数据翻译

环境:python3.6
2.x的urllib包和3.x是有区别的,3.x的urllib包里面的request===2.x的urllib2包

1. 获取请求地址链接

2. 分析参数,组装链接地址

3. 获取请求参数结果

4. 解析返回结果

  1. 构造网络请求地址链接,这次用的是有道翻译的http请求
    host = 'http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&q='+word

  2. 声明方法来获取请求结果,我们需要引入python的urllib包,urllib

from urllib import request , parse
def fetch(word):
    req = request.openUrl(host+word)
    res = req.read().decode('utf-8')
    return res
  1. 声明方法获取解析结果
    我们先来看下如果直接调用链接返回来的数据是什么样的形式
http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&q=word
{"translation":["词"],
"basic":{"us-phonetic":"wɝd","phonetic":"wɜːd","uk-phonetic":"wɜːd",
"explains":["n. [语] 单词;话语;消息;诺言;命令","vt. 用言辞表达","n. (Word)人名;(英)沃德"]},
"query":"word",
"errorCode":0,
"web":[{"value":["单词","字","字 (计算机)"],"key":"word"},
{"value":["构词法","造词法","词性转换"],"key":"Word Formation"},
{"value":["关键字","中心词","关键词"],"key":"key word"}]}

有道那边返回来的是json数据,我们需要把他们转换成dict,通过json包,通过判断返回来的errorCode判断是否有数据

import json
def parse(html):
    try:
        j_content = json.loads(html)#json转dict用loads,dict转json用dumps
        p_errorCode = j_content.get('errorCode')
        if p_errorCode != 0 :
            print('解析出错')
        else:
            p_translation = j_content.get('translation')
            p_basic = j_content.get('basic')
            p_explains = p_basic.get('explains')
            p_query = j_content.get('query')
            p_web = j_content.get('web')
            for c in p_explains:
                print(c)
except exception as e:
    print('解析出错')
  1. 命令行处理,声明入口函数
if __name__ == '__main__':
    main()
def main():
    try:
        word = sys.argv[1]
        c_content = fetch(word)
        parse(c_content)
    except IndexError as e:
        print(e.args)
  1. 最后我们来看下效果


你可能感兴趣的:(【基础】python实现命令行数据翻译)