百度翻译api调用例子

# -*- coding: utf-8 -*-
import requests
import random
import json
from hashlib import md5

            
# 这里的appid和appkey是自己在官网申请的appid以及securityKey
appid = 'xxxxxxxxxxxxxxx'
appkey = 'xxxxxxxxxxxxxxx'

# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang =  'zh'
endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

#询问的问题
query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.\nThis is 3nd paragraph.\nThis is 4nd paragraph.'

# 生成器
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()

salt = random.randint(222222, 999999)
sign = make_md5(appid + query + str(salt) + appkey)

# Build request
headers = {'Content-Type': 'application/x-www-form-urlencoded'}
payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

# Send request
r = requests.post(url, params=payload, headers=headers)
result = r.json()


##response = requests.get(url, params=payload, headers=headers)
##result = json.loads(response.text)

# 解析API返回的结果
if 'error_code' in result:
    print('Translation failed. Error code:', result['error_code'])
else:
    a=0
    print(result['trans_result'][0]['dst'])
    while result['trans_result'][a]['dst']!=result['trans_result'][-1]['dst']:
        print(result['trans_result'][a+1]['dst'])
        a+=1
        

 

 

自己改写了appid和key就行了

当然问题得内容要做成动态 就自己搞了,我这就可以了

20230504代码有效 python 3.8.10

需要下载个第三方包

pip install requests

posted @ 2023-05-04 23:58  三天泪  阅读(75)  评论(0编辑  收藏  举报