Python3调用百度翻译API进行英文翻译

    xiaoxiao2022-07-14  192

    一.API的概念

          API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力,而又无需访问源码,或理解内部工作   机制的细节。

    二.百度翻译开放平台

        由API的概念可以知道,很多大型的平台都提供API接口。这里使用的是百度翻译的API接口。下面提供百度翻译开放平台的

    网址:http://api.fanyi.baidu.com/api/trans/product/index。进入平台后,点击【立即使用】,申请ID和SECRECT KEY,申请到了就可以通过ID和密钥调用API接口实现相应功能了。

    下图是我的开发者信息里面的ID和密钥。

    在开发平台上有【文件支持】栏,通过该栏目,可以找到各种API接口的技术文档,可以根据技术文档的要求设置,设置接入方式。

    三.程序编写

    1.地址设置

    首先设置url地址,和申请到的ID和密钥。

    # set baidu develop parameter apiurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate' appid = '你的ID' secretKey = '你的密钥'

    因为翻译代码要频繁调用,这里单独列为一个函数:

    # 翻译内容 源语言 翻译后的语言 def translateBaidu(content, fromLang='en', toLang='zh'): salt = str(random.randint(32768, 65536)) sign = appid + content + salt + secretKey #appid+q+salt+密钥 的MD5值 sign = hashlib.md5(sign.encode("utf-8")).hexdigest() #对sign做md5,得到32位小写的sign try: #根据技术手册中的接入方式进行设定 paramas = { 'appid': appid, 'q': content, 'from': fromLang, 'to': toLang, 'salt': salt, 'sign': sign } response = requests.get(apiurl, paramas) jsonResponse = response.json() # 获得返回的结果,结果为json格式 dst = str(jsonResponse["trans_result"][0]["dst"]) # 取得翻译后的文本结果 return dst except Exception as e: print(e)

    这里使用的源文件是英文语句存在【name.xlsx】文件中,翻译后的文档也会存入到【name1.xlsx】中。其中,【openpyxl】模块包是功能强大的excel处理包,这里用该模块对文件进行处理。

    def excelTrans( srcFilename=r'F:\日常··练习\api\Python3 调用百度翻译Excel文件\source.xlsx', desFilename=r'F:\日常··练习\api\Python3 调用百度翻译Excel文件\result.xlsx', srcSheet='Sheet1', numColumn = 2, srcRowBegin=1, srcRowEnd=44, desColumn=1, desSheet='result2'): wb = openpyxl.load_workbook(srcFilename) ws = wb[srcSheet] wb2 = Workbook() #ws2 = wb2.create_sheet(title=desSheet) #ws2 = wb2.create_sheet(title=desSheet,index = 1) for j in range(numColumn ): ws2 = wb2.create_sheet(title=desSheet,index = j) for i in range(srcRowBegin, srcRowEnd, 1): result = ws.cell(row=i, column=j+1).value if not (result is None): ws2.cell(row=i-srcRowBegin+1, column=desColumn).value = translateBaidu(result) print(11, result) wb2.save(desFilename)

    该函数实现了将目标excel中的英文句子翻译为中文,并按列分别存储在不同sheet中:

    使用的包和完整代码如下

    #!/usr/bin/env python # -*- coding: utf-8 -*- import hashlib import random import openpyxl from openpyxl import Workbook import requests # set baidu develop parameter apiurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate' appid = '你的ID' secretKey = '你的密钥' # 翻译内容 源语言 翻译后的语言 def translateBaidu(content, fromLang='en', toLang='zh'): salt = str(random.randint(32768, 65536)) sign = appid + content + salt + secretKey sign = hashlib.md5(sign.encode("utf-8")).hexdigest() try: paramas = { 'appid': appid, 'q': content, 'from': fromLang, 'to': toLang, 'salt': salt, 'sign': sign } response = requests.get(apiurl, paramas) jsonResponse = response.json() # 获得返回的结果,结果为json格式 dst = str(jsonResponse["trans_result"][0]["dst"]) # 取得翻译后的文本结果 return dst except Exception as e: print(e) def excelTrans( srcFilename=r'F:\日常··练习\api\Python3 调用百度翻译Excel文件\source.xlsx', desFilename=r'F:\日常··练习\api\Python3 调用百度翻译Excel文件\result.xlsx', srcSheet='Sheet1', num = 2, #srcColumn=2, srcRowBegin=1, srcRowEnd=44, desColumn=1, desSheet='result2'): wb = openpyxl.load_workbook(srcFilename) ws = wb[srcSheet] wb2 = Workbook() #ws2 = wb2.create_sheet(title=desSheet) #ws2 = wb2.create_sheet(title=desSheet,index = 1) for j in range(num): ws2 = wb2.create_sheet(title=desSheet,index = j) for i in range(srcRowBegin, srcRowEnd, 1): result = ws.cell(row=i, column=j+1).value if not (result is None): ws2.cell(row=i-srcRowBegin+1, column=desColumn).value = translateBaidu(result) print(11, result) wb2.save(desFilename) if __name__ == '__main__': print('translate begin...') excelTrans() print('ending...')

     

    最新回复(0)