本篇文章给大家分享的是有关怎么在python3中调用百度翻译API实现实时翻译,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
# coding: utf8 ''' @Author: LCY @Contact: lchuanyong@126.com @blog: http://http://blog.csdn.net/lcyong_ @Date: 2018-01-15 @Time: 19:19 说明: appid和secretKey为百度翻译文档中自带的,需要切换为自己的 python2和python3部分库名称更改对应如下: httplib ----> http.client md5 ----> hashlib.md5 urllib.quote ----> urllib.parse.quote 官方链接: http://api.fanyi.baidu.com/api/trans/product/index ''' import http.client import hashlib import json import urllib import random def baidu_translate(content): appid = '20151113000005349' secretKey = 'osubCEzlGjzvw8qdQc41' httpClient = None myurl = '/api/trans/vip/translate' q = content fromLang = 'zh' # 源语言 toLang = 'jp' # 翻译后的语言 salt = random.randint(32768, 65536) sign = appid + q + str(salt) + secretKey sign = hashlib.md5(sign.encode()).hexdigest() myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote( q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str( salt) + '&sign=' + sign try: httpClient = http.client.HTTPConnection('api.fanyi.baidu.com') httpClient.request('GET', myurl) # response是HTTPResponse对象 response = httpClient.getresponse() jsonResponse = response.read().decode("utf-8")# 获得返回的结果,结果为json格式 js = json.loads(jsonResponse) # 将json格式的结果转换字典结构 dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果 print(dst) # 打印结果 except Exception as e: print(e) finally: if httpClient: httpClient.close() if __name__ == '__main__': while True: print("请输入要翻译的内容,如果退出输入q") content = input() if (content == 'q'): break baidu_translate(content)
官方版本:
#/usr/bin/env python #coding=utf8 import httplib import md5 import urllib import random appid = '20151113000005349' secretKey = 'osubCEzlGjzvw8qdQc41' httpClient = None myurl = '/api/trans/vip/translate' q = 'apple' fromLang = 'en' toLang = 'zh' salt = random.randint(32768, 65536) sign = appid+q+str(salt)+secretKey m1 = md5.new() m1.update(sign) sign = m1.hexdigest() myurl = myurl+'?appid='+appid+'&q='+urllib.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign try: httpClient = httplib.HTTPConnection('api.fanyi.baidu.com') httpClient.request('GET', myurl) #response是HTTPResponse对象 response = httpClient.getresponse() print response.read() except Exception, e: print e finally: if httpClient: httpClient.close()
以上就是怎么在python3中调用百度翻译API实现实时翻译,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。