import random
import hashlib
import http.client, urllib.parse
import json
class baidu_trans:
# 接口地址
domain = 'api.fanyi.baidu.com'
uri = "/api/trans/vip/translate"
# 密钥相关
app_id = ""
app_screct = ""
salt = random.randint(32768, 65536)
# 错误码
errors_code = {
"52000": "成功",
"52001": "请求超时",
"52002": "系统错误",
"52003": "未授权用户",
"54000": "必填参数为空",
"54001": "签名错误",
"54003": "访问频率受限",
"54004": "账户余额不足",
"54005": "长query请求频繁",
"58000": "客户端IP非法",
"58001": "译文语言方向不支持",
"58002": "服务当前已关闭",
"90107": "认证未通过或未生效",
}
# 生成签名
def getSign(self,context):
sign = self.app_id + context + str(self.salt) + self.app_screct
md5_obj = hashlib.md5()
md5_obj.update(sign.encode('utf-8'))
return md5_obj.hexdigest()
pass
# 将文本翻译为指定的语言
def trans(self,context):
httpClient = None
form = {
"q": context,
"from": "en",
"to": "zh",
"appid": self.app_id,
"salt": self.salt,
"sign": self.getSign(context),
}
try:
url = self.uri + '?appid=' + form["appid"] + '&q=' + urllib.parse.quote(form["q"]) + '&from=' + form["from"] + '&to=' + form["to"] + '&salt=' + str(form["salt"]) + '&sign=' + form['sign']
httpClient = http.client.HTTPConnection(self.domain)
httpClient.request('GET', url)
response = httpClient.getresponse()
result = json.loads(bytes.decode(response.read()))
if 'error_code' in result:
print('错误'+result["error_code"]+':' + self.errors_code[result["error_code"]] )
return result["trans_result"][0]['dst']
except Exception as e:
print(e)
finally:
if httpClient:
httpClient.close()
pass
pass
python3.7.4 百度翻译api
短信预约 -IT技能 免费直播动态提醒
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341