欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python3调用百度翻译API实现实时翻译

程序员文章站 2023-08-27 18:57:19
今天需要做一个翻译的工具,找到之前写过的有道翻译,已经不能用了,最后看到百度翻译还不错,不过官方版本是python2,我需要python3,就自己写了一个: #...

今天需要做一个翻译的工具,找到之前写过的有道翻译,已经不能用了,最后看到百度翻译还不错,不过官方版本是python2,我需要python3,就自己写了一个:

# 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()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。