#!/usr/bin/env python3 # -*- coding: utf-8 -*- import urllib.request import urllib.parse import json import sys def BDTrans(words): params = urllib.parse.urlencode({'client_id':'0ZinyoGLHU9zZkfuBpfzKhuB','q':words,'from': 'auto','to':'auto'}) f = urllib.request.urlopen("http://openapi.baidu.com/public/2.0/bmt/translate?%s" % params, timeout=5) s=json.loads(f.read().decode('utf-8')) print('来自百度翻译:\n\n\t'+s['trans_result'][0]['dst']) def BDDict(word): params = urllib.parse.urlencode({'client_id':'0ZinyoGLHU9zZkfuBpfzKhuB','q':word,'from': 'auto','to':'auto'}) f = urllib.request.urlopen("http://openapi.baidu.com/public/2.0/translate/dict/simple?%s" % params, timeout=5) s=json.loads(f.read().decode('utf-8')) print('来自百度词典:\n\n\t'+'英式发音:'+s['data']['symbols'][0]['ph_en']+' 美式发音:'+s['data']['symbols'][0]['ph_am']+'\n') contentls=s['data']['symbols'][0]['parts'] for item in contentls: res='' for i in item['means']: res+=i+'; ' print('\t'+item['part']+' '+res+'\n') def YDTrans(cont): params = urllib.parse.urlencode({'keyfrom':'PyTrans','key':'1531046399','type': 'data','doctype':'json','version':'1.1','q':cont}) f = urllib.request.urlopen("http://fanyi.youdao.com/openapi.do?%s" % params, timeout=5) s=json.loads(f.read().decode('utf-8')) strtmp='' for i in s['translation']: strtmp+=i+'; ' print('有道翻译:\n\n\t'+strtmp+'\n') print('有道词典:\n\n\t'+'英式发音:'+s['basic']['uk-phonetic']+' 美式发音:'+s['basic']['us-phonetic']+'\n') for i in s['basic']['explains']: print('\t'+i) print('\n有道词典-网络释义:') strtmp1='' for i in s['web']: for j in i['value']: strtmp1+=j+'; ' print('\n\t'+i['key']+'\n\t'+strtmp1) if __name__=="__main__": if(len(sys.argv))!=2: print('命令行有误,请正确输入要查询的词或句子') else: BDTrans(sys.argv[1]) BDDict(sys.argv[1]) YDTrans(sys.argv[1])