python3使用百度翻译API实现自动翻译

百度翻译开放平台

  • 注册登录,创建个人服务
  • 查看技术文档
  • 接口参数配置
  • 实例应用
    • 翻译一个单词
    • 翻译一句话
    • 翻译一段话

注册登录,创建个人服务

在此不详细赘述!(获取APP ID和密钥)
python3使用百度翻译API实现自动翻译_第1张图片

查看技术文档

需要注意的是:每个月的免费额度是200万字符,不要超了,或者注册多个账户。
python3使用百度翻译API实现自动翻译_第2张图片

接口参数配置


def translate_api(text):
    """英文翻译成中文"""
    appid = ''#你的id
    secretKey = ''#你的密钥
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    q = text
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
    sign = appid+q+str(salt)+secretKey
    m1 = md5()
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()

    myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    return myurl

实例应用

翻译一个单词


import json
import random
import requests
import urllib.parse
from hashlib import md5



def translate_api(text):
    appid = ''
    secretKey = ''
    myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate'
    q = text
    fromLang = 'en'
    toLang = 'zh'
    salt = random.randint(32768, 65536)
    sign = appid+q+str(salt)+secretKey
    m1 = md5()
    m1.update(sign.encode("utf-8"))
    sign = m1.hexdigest()

    myurl = myurl+'?appid='+appid+'&q='+urllib.parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    return myurl


text = 'summary'
myurl = translate_api(text)
response = requests.get(myurl)
rans_result = json.loads(response.text)['trans_result'][0]['dst']
print(rans_result)
总结

翻译一句话


text = 'A rich man is absolutely willful'
myurl = translate_api(text)
response = requests.get(myurl)
rans_result = json.loads(response.text)['trans_result'][0]['dst']
print(rans_result)
有钱人绝对是任性的。

翻译一段话

这么专业的学术用语,都可以流畅的翻译,以后再也不用怕读英文文献了……

text = 'This gene encodes a cytokine distantly related to type I interferons and the IL-10 family. This gene interleukin 28A (IL28A) and interleukin 29 (IL29) are three closely related cytokine genes that form a cytokine gene cluster on a chromosomal region mapped to 19q13. Expression of the cytokines encoded by the three genes can be induced by viral infection. All three cytokines have been shown to interact with a heterodimeric class II cytokine receptor that consists of interleukin 10 receptor beta (IL10RB) and interleukin 28 receptor alpha (IL28RA). [provided by RefSeq Jul 2008]'
myurl = translate_api(text)
response = requests.get(myurl)
rans_result = json.loads(response.text)['trans_result'][0]['dst']
print(rans_result)
该基因编码与I型干扰素和IL-10家族远亲相关的细胞因子。该基因白细胞介素28AIL28A)和白细胞介素29(IL29)是三个密切相关的细胞因子基因,它们在染色体上形成细胞因子基因簇,定位为19q13。三种基因编码的细胞因子的表达可通过病毒感染诱导。所有三种细胞因子都显示与由白细胞介素10受体β(IL10RB)和白细胞介素28受体α(IL28RA)组成的异二聚II类细胞因子受体相互作用。[由Refsq Jul 2008提供]

你可能感兴趣的:(python实用技能)