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

环境:python3.6

2.x的urllib包和3.x是有区别的,3.x的urllib包里面的request===2.x的urllib2包

1. 获取请求地址链接

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

3. 获取请求参数结果

4. 解析返回结果

构造网络请求地址链接,这次用的是有道翻译的http请求

host = 'http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&q='+word

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

from urllib import request , parse

def fetch(word):

req = request.openUrl(host+word)

res = req.read().decode('utf-8')

return res

声明方法获取解析结果

我们先来看下如果直接调用链接返回来的数据是什么样的形式

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('解析出错')

命令行处理,声明入口函数

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)

最后我们来看下效果

6d6cad94c2c4034d205d23666bf33c13.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值