利用python及百度翻译api实现名场面自动翻译20遍

1.在百度翻译api官网http://api.fanyi.baidu.com/api/trans/product/index注册,获取appid及密钥

2.在python官网下载任意版本编译器

3输入以下代码

import requests

import refrom json import loads

import json

import http.client

import hashlib

import urllib

import random

def C_to_E(q):

appid = '*************'  # 填写你的appid

secretKey = '****************'  # 填写你的密钥

httpClient = None

myurl = '/api/trans/vip/translate'

fromLang = 'zh'   #原文语种

toLang = 'en'   #译文语种

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

result_all = response.read().decode("utf-8")

result = json.loads(result_all)

her_anser=result['trans_result']

her_anser=her_anser[0]

her_anser=her_anser['dst']

return her_anser

except Exception as e:

print (e)

finally:

if httpClient:

httpClient.close()

def E_to_C(q):

appid = '****************'  # 填写你的appid

secretKey = '*****************'  # 填写你的密钥

httpClient = None

myurl = '/api/trans/vip/translate'

fromLang = 'en'   #原文语种

toLang = 'zh'   #译文语种

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

result_all = response.read().decode("utf-8")

result = json.loads(result_all)

her_anser=result['trans_result']

her_anser=her_anser[0]

her_anser=her_anser['dst']

return her_anser

except Exception as e:

print (e)

finally:

if httpClient:

httpClient.close()

if __name__ == '__main__':

txt=input('请输入中文:')

for i in range(1,20):

if i%2==0:

txt=C_to_E(txt)

else:

txt=E_to_C(txt)

print (txt)

本文禁止转载或摘编

--

--

--

分享到:

投诉或建议

评论

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐