Python call Baidu translation interface translation

Small series were written Word, Baidu translation Demo, personally I feel there are so few differences:

  • The amount of code: Baidu more concise and proper way too redundant;
  • Whether charges: free translation proper way, Baidu translated more than a certain amount should be charged, so to verify key;
  • Normative: proper way compared to translation, translation Baidu API more formal channels, personal feel.

Baidu key application:

Since Baidu translation requires authentication key, we will need to apply for an account, get keys:

Baidu open platform translation: http://api.fanyi.baidu.com/api/trans/product/index

Process is as follows:

  1. Follow the prompts to register an account, get APP ID and keys;
  2. Subscribe to universal translator API service;
  3. Reference Baidu translation provided by the universal translator API Technical Documentation  access, or reference me the following Demo.

Demo:

My environment is Py3 , Demo need to complement their appid and secretKey, then copied directly to run, not missing a line of code.

#百度通用翻译API,不包含词典、tts语音合成等资源,如有相关需求请联系[email protected]
# coding=utf-8

import http.client
import hashlib
import urllib
import random
import json
from pip._vendor.distlib.compat import raw_input

# 百度appid和密钥需要通过注册百度【翻译开放平台】账号后获得
appid = 'xxxxxx'        # 填写你的appid
secretKey = 'xxxxxx'    # 填写你的密钥

httpClient = None
myurl = '/api/trans/vip/translate'  # 通用翻译API HTTP地址

fromLang = 'auto'       # 原文语种
toLang = 'zh'           # 译文语种
salt = random.randint(32768, 65536)
# 手动录入翻译内容,q存放
q = raw_input("please input the word you want to translate:")
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)

    print (result)

except Exception as e:
    print (e)
finally:
    if httpClient:
        httpClient.close()

List of languages

Can be set to auto, language can not be set as the target language to the source language language auto uncertain. Because for a very language, language automatically detects possible errors.

Shorthand language name
auto automatic detection
zh Chinese
in English
yue In Cantonese
withered Classical
jp Japanese
disease Korean
from French
spa Spanish
th Thai
now Arabic
ru Russian
pt Portuguese
from German
it Italian language
the Greek
nl Dutch
pl Polish
find Bulgarian
East Estonian
and Danish
end Finnish
cs Czech
rom Romanian
slo Slovenian
his Swedish
hu Hungarian
Cht traditional Chinese
life Vietnamese language

Error Code List

When the translation results can not return to normal, please refer to the following table processing:

error code meaning Solution
52000 success  
52001 Request timed out Retry
52002 system error Retry
52003 Unauthorized users Check your  appid  is correct, or whether the service is launched
54000 Required parameter is empty Check that few pass parameters
54001 签名错误 请检查您的签名生成方法
54003 访问频率受限 请降低您的调用频率
54004 账户余额不足 请前往管理控制台为账户充值
54005 长query请求频繁 请降低长query的发送频率,3s后再试
58000 客户端IP非法 检查个人资料里填写的 IP地址 是否正确可前往管理控制平台修改IP限制,IP可留空
58001 译文语言方向不支持 检查译文语言是否在语言列表里
58002 服务当前已关闭 请前往管理控制台开启服务
90107 认证未通过或未生效 请前往我的认证查看认证进度

常见问题

见通用翻译API技术文档:http://api.fanyi.baidu.com/api/trans/product/apidoc

 

更多精彩,请关注我的"今日头条号":Java云笔记
随时随地,让你拥有最新,最便捷的掌上云服务

 

发布了165 篇原创文章 · 获赞 270 · 访问量 8万+

Guess you like

Origin blog.csdn.net/weixin_44259720/article/details/104648444