python 调用有道api接口的方法

yipeiwu_com6年前Python基础

初学python ,研究了几天,写了一个python 调用 有道api接口程序

效果看下图:

python 调用有道api接口

申明:代码仅供和我一样的初学者学习交流

有道api申请地址http://fanyi.youdao.com/openapi?path=data-mode

申请很简单的 ps:审核不用花时间的,请勿滥用!!

#-*- coding: UTF-8 -*- 
import urllib
import urllib2
import requests 
import json
import sys 
reload(sys) 
sys.setdefaultencoding("utf-8")  
#print(sys.getdefaultencoding())
def youdao(text,c=1):  #c 1 翻译 2查词 
	#textx=text.decode('gbk').encode('utf-8')  #将gbk编码转utf-8 编码  有道api要求传入 utf-8 编码	
	from urllib import quote
	#t=quote(textx)
	t=quote(text)
	url="接口" #这个链接自己申请哈
	r = requests.get(url)
	if r.status_code==200:
		res=json.loads(r.text,encoding='utf-8')
		errorCode=res['errorCode']
		title='『小风翻译』\n\n'
		yd='\n数据来源 有道'  #这句必须有,对有道提供免费的api接口表示感谢。
		if errorCode==0:
			query=res['query'] #分析翻译 
			translation=res['translation']
			trans=u'原文:%s\n翻译:%s' % (query,translation[0])
			trans_s=trans#.encode('GB18030')
 
			basic_s=''
			if 'basic' in res:  #分析有基础释义部分
				phonetic=res['basic']['phonetic']
				explains=res['basic']['explains']
				phone_s=u'%s  %s\n---基本释义---\n' % (query,phonetic)
				for x in explains:
					basic_s=basic_s+x+'\n'
				basic_s=phone_s+basic_s  #基本释义
			
			web_s=' '	
			if 'web' in res:
				web_s='---网络释义---\n'
				web=res['web']
				for x in web:
					web_k=x['key']
					web_v=x['value']
					value=''
					for v in web_v:
						value=value+v+'; '
					web_s=web_s+'√ '+web_k+'\n释义:'+value+'\n'
			if c==1:
				send=title+trans_s+'\n\n'+web_s+yd
				return send#.encode('GB18030')
			else:
				send=title+basic_s+'\n'+web_s+yd
				return send#.encode('GB18030')
		elif errorCode==20:
			return '亲,输入的字数过长了,小风做不到啊ヽ(≧□≦)ノ'
		elif errorCode==30:
			return 'What? 翻译失败了,再试一次吧(⊙o⊙)'
		else :
			return '服务器异常,错误%i,请联系QQ1849059316' % errorCode
	else :
		return '访问出错!请联系QQ1849059316'
print youdao('include')

注意:requests 库必须先安装

>>这里提供用ipi的方式安装,这种方式简单!另外的方式请移步百度,毕竟一抓一大把的东西没必要写了

方法:打开命令行 直接键入 pip install requests 然后就ok了 哈哈

以上这篇python 调用有道api接口的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Jupyter中直接显示Matplotlib的图形方法

Jupyter中直接显示Matplotlib的图形方法

一.使用以下cmd命令生成ipython_config.py 文件 ipython profile create 二.在ipython_config.py中添加以下代码 c....

6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)

6行Python代码实现进度条效果(Progress、tqdm、alive-progress​​​​​​​和PySimpleGUI库)

在项目开发过程中加载、启动、下载项目难免会用到进度条,如何使用Python实现进度条呢? 这里为小伙伴们分享四种Python实现进度条的库:Progress库、tqdm库、alive-p...

在Python中使用poplib模块收取邮件的教程

在Python中使用poplib模块收取邮件的教程

SMTP用于发送邮件,如果要收取邮件呢? 收取邮件就是编写一个MUA作为客户端,从MDA把邮件获取到用户的电脑或者手机上。收取邮件最常用的协议是POP协议,目前版本号是3,俗称POP3。...

python实现列表中由数值查到索引的方法

python实现列表中由数值查到索引的方法

如下所示: 以上这篇python实现列表中由数值查到索引的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。...

详解windows python3.7安装numpy问题的解决方法

详解windows python3.7安装numpy问题的解决方法

我的是win7的系统,去python官网下载python3.7安装 CMD  #打开命令窗口 pip install numpy #在cmd中输入 提示 需要c++14....