溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python中如何批量將excel內(nèi)容進(jìn)行翻譯寫入功能

發(fā)布時(shí)間:2021-07-10 11:25:42 來(lái)源:億速云 閱讀:309 作者:小新 欄目:開發(fā)技術(shù)

這篇文章將為大家詳細(xì)講解有關(guān)python中如何批量將excel內(nèi)容進(jìn)行翻譯寫入功能,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

1.首先是需要進(jìn)行文件的讀寫操作,需要獲取文件路徑,方式使用os.listdir(路徑)進(jìn)行批量查找文件。

file_path = ‘/home/xx/xx/xx'
# ret 返回一個(gè)列表
ret = list_dir = os.listdir(file_path)
# 遍歷列表,獲取需要的結(jié)尾文件(只考慮獲取文件,不考慮執(zhí)行效率)
for i in ret :
    if i.endswith('xlsx'):
    # 執(zhí)行的邏輯

2.改寫一下我調(diào)用的翻譯接口

def baidu_translate(appi, secretKe, content):
  appid = appi
  secretKey = secretKe
  httpClient = None
  myurl = '/api/trans/vip/translate'
  q = content
  fromLang = 'zh' # 源語(yǔ)言
  toLang = 'en' # 翻譯后的語(yǔ)言
  salt = random.randint(32768, 65536)
  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.baidu_translation.baidu.com')
    httpClient.request('GET', myurl)
    response = httpClient.getresponse()
    jsonResponse = response.read().decode("utf-8") # 獲得返回的結(jié)果,結(jié)果為json格式
    js = json.loads(jsonResponse) # 將json格式的結(jié)果轉(zhuǎn)換字典結(jié)構(gòu)
    dst = str(js["trans_result"][0]["dst"]) # 取得翻譯后的文本結(jié)果
    print(dst) # 打印結(jié)果
    return dst
  except Exception as e:
    print(e)
  finally:
    if httpClient:
      httpClient.close()

3.現(xiàn)在需要進(jìn)行讀取excel的內(nèi)容,使用方法,xlrd,小編使用的翻譯是借用的百度翻譯的API,獲取excel內(nèi)容,傳遞給API

import hashlib
import http.client
import json
import os
import random
import time
import urllib
import openpyxl
import xlrd
# 借用上邊所述的文件路徑操作
# appid :翻譯API提供,需要注冊(cè)獲取
# secretKey :翻譯API提供,需要注冊(cè)獲取
def read_excel(file_path, appid, secretKey):
  list_dir = os.listdir(file_path)
  for i in list_dir:
    if i.endswith('.xlsx'):
     # 拼接獲取絕對(duì)路徑
      file_path = file_path + '\\' + i
      rbook = xlrd.open_workbook(filename=file_path)
      rbook.sheets()
      # 獲取excel某頁(yè)數(shù)據(jù)
      sheet1 = rbook.sheet_by_index(0)
      row_num = sheet1.nrows
      for num in range(row_num):
        try:
         # 小編這樣寫的原因是我值獲取指定列的數(shù)據(jù),
         # 例如現(xiàn)在獲取第3,4列數(shù)據(jù)
          txt1 = sheet1.cell_value(num, 3)
          txt2 = sheet1.cell_value(num, 4)
          # 為了2列數(shù)據(jù)可以同時(shí)進(jìn)行翻譯
          txt = txt1 + '=' + txt2
          # ret返回翻譯結(jié)果
          ret = baidu_translate(appid, secretKey, txt)  
          
          # 防止調(diào)用接口出錯(cuò)
          time.sleep(1)
          # 將翻譯結(jié)果在寫如excel
          write_excel(ret, num, file_path)
        except Exception as e:
          print(e)
          continue

4.因?yàn)樯弦徊秸{(diào)用了這個(gè)寫入excel的函數(shù),所有我們需要寫一個(gè)函數(shù)來(lái)完成寫入的操作。

def write_excel(ret, num, file_path):
  f_txt = file_path
  book = openpyxl.load_workbook(f_txt)
  sheet1 = book.worksheets[0]
  # 在這個(gè)地方是獲取某列寫入
  txtE = 'F' + str(num + 1)
  txtF = 'G' + str(num + 1)
  s_txt = ret.split('=')
  sheet1[txtE] = s_txt[0]
  sheet1[txtF] = s_txt[1]
  book.save(f_txt)
  
if __name__ == '__main__':
  appid = 'xxxx'
  secretKey = 'xxxx'
  path = r'xxx'
  read_excel(path, appid, secretKey)

關(guān)于“python中如何批量將excel內(nèi)容進(jìn)行翻譯寫入功能”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI