Python3调用百度翻译API进行英文翻译
一.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位小寫的signtry:#根據技術手冊中的接入方式進行設定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 dstexcept 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).valueif 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 + secretKeysign = 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 dstexcept 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).valueif 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...')
?
總結
以上是生活随笔為你收集整理的Python3调用百度翻译API进行英文翻译的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java开发可以转什么软件有哪些_转行开
- 下一篇: mysql group和order_my