python调用API翻译到中文(中、英、日、韩、西、法、泰、阿)

服务介绍:
支持28种语言实时互译,覆盖中、英、日、韩、西、法、泰、阿、俄、葡、德、意、荷、芬、丹等;同时支持28种语言的语言检测。
「 广泛适用于各领域有翻译需求的开发者 」
2019年7月2日起,通用翻译API升级为标准版、高级版和尊享版三个版本:
标准版:提供基础文本翻译服务,QPS(每秒并发请求量)=1,个人或企业用户均可申请使用
高级版:提供基础文本翻译服务,同时可申请自定义术语功能,QPS=10,供个人认证用户申请使用
尊享版:提供基础文本翻译服务,同时可申请词典、语音合成、自定义术语功能,QPS=100,供企业认证用户申请使用
收费模式:
标准版:免费,不限字数

[En]

Standard version: free of charge, unlimited number of characters

高级版和高级版:每月翻译字数低于200万字,享受免费服务;超过200万字,按49元/百万字收取当月超出字数的费用。

[En]

Premium version and premium version: enjoy free service if the number of characters translated per month is less than 2 million; if the number of characters exceeds 2 million characters, the fee for the excess of characters in the current month will be paid according to 49 yuan / million characters.

标准版更认真,你可以每秒查一次词,而且是免费的。

[En]

The standard version is more conscientious, you can look up words once a second, and it’s free.


import json
import http.client
import hashlib
from urllib import parse
import random

def translate(q):

    appid = '***'
    secretKey = '*****'

    httpClient = None
    myurl = '/api/trans/vip/translate'
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)

    sign = appid+q+str(salt)+secretKey
    m1 = hashlib.md5()
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()

    myurl = myurl+'?appid='+appid+'&q='+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 = httpClient.getresponse()

        html = response.read().decode('utf-8')
        html = json.loads(html)
        dst = html["trans_result"][0]["dst"]
        return dst
    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()

print(translate("cat"))

执行上面的代码,如果最后输出“cat”,就可以正常使用了。

[En]

Execute the above code, if the final output “cat”, it can be used normally.

在大规模调用API的时候,需要注意标准版的QPS(每秒并发请求量)=1,所以查询一次之后需要休眠一秒钟,才能继续查询,否则会出错。

from translate import translate
import time
i = 0
while 1:
    time.sleep(1)
    trans = translate(text)
    i += 1
    if text == None:
        break
    if i >= 389140:
        break

Original: https://blog.csdn.net/qq_40608730/article/details/123170585
Author: HNU_刘yuan
Title: python调用API翻译到中文(中、英、日、韩、西、法、泰、阿)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/498042/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球