python批量将excel内容进行翻译写入功能

yipeiwu_com6年前Python基础

由于小编初来乍到,有很多地方不是很到位,还请见谅,但是很实用的哦!

1.首先是需要进行文件的读写操作,需要获取文件路径,方式使用os.listdir(路径)进行批量查找文件。

file_path = ‘/home/xx/xx/xx'
# ret 返回一个列表
ret = list_dir = os.listdir(file_path)
# 遍历列表,获取需要的结尾文件(只考虑获取文件,不考虑执行效率)
for i in ret :
    if i.endswith('xlsx'):
    # 执行的逻辑

2.改写一下我调用的翻译接口

def baidu_translate(appi, secretKe, content):
  appid = appi
  secretKey = secretKe
  httpClient = None
  myurl = '/api/trans/vip/translate'
  q = content
  fromLang = 'zh' # 源语言
  toLang = 'en' # 翻译后的语言
  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") # 获得返回的结果,结果为json格式
    js = json.loads(jsonResponse) # 将json格式的结果转换字典结构
    dst = str(js["trans_result"][0]["dst"]) # 取得翻译后的文本结果
    print(dst) # 打印结果
    return dst
  except Exception as e:
    print(e)
  finally:
    if httpClient:
      httpClient.close()

3.现在需要进行读取excel的内容,使用方法,xlrd,小编使用的翻译是借用的百度翻译的API,获取excel内容,传递给API

import hashlib
import http.client
import json
import os
import random
import time
import urllib
import openpyxl
import xlrd
# 借用上边所述的文件路径操作
# appid :翻译API提供,需要注册获取
# secretKey :翻译API提供,需要注册获取
def read_excel(file_path, appid, secretKey):
  list_dir = os.listdir(file_path)
  for i in list_dir:
    if i.endswith('.xlsx'):
     # 拼接获取绝对路径
      file_path = file_path + '\\' + i
      rbook = xlrd.open_workbook(filename=file_path)
      rbook.sheets()
      # 获取excel某页数据
      sheet1 = rbook.sheet_by_index(0)
      row_num = sheet1.nrows
      for num in range(row_num):
        try:
         # 小编这样写的原因是我值获取指定列的数据,
         # 例如现在获取第3,4列数据
          txt1 = sheet1.cell_value(num, 3)
          txt2 = sheet1.cell_value(num, 4)
          # 为了2列数据可以同时进行翻译
          txt = txt1 + '=' + txt2
          # ret返回翻译结果
          ret = baidu_translate(appid, secretKey, txt)  
          
          # 防止调用接口出错
          time.sleep(1)
          # 将翻译结果在写如excel
          write_excel(ret, num, file_path)
        except Exception as e:
          print(e)
          continue

4.因为上一步调用了这个写入excel的函数,所有我们需要写一个函数来完成写入的操作。

def write_excel(ret, num, file_path):
  f_txt = file_path
  book = openpyxl.load_workbook(f_txt)
  sheet1 = book.worksheets[0]
  # 在这个地方是获取某列写入
  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)

总结

以上所述是小编给大家介绍的python批量将excel内容进行翻译写入功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对【听图阁-专注于Python设计】网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

相关文章

Python基础教程之内置函数locals()和globals()用法分析

本文实例讲述了Python基础教程之内置函数locals()和globals()用法。分享给大家供大家参考,具体如下: 1. 这两个函数主要提供,基于字典的访问局部变量和全局变量的方式。...

新手如何发布Python项目开源包过程详解

新手如何发布Python项目开源包过程详解

本文假设你在 GitHub 上已经有一个想要打包和发布的项目。 第 0 步:获取项目许可证 在做其他事之前,由于你的项目要开源,因此应该有一个许可证。获取哪种许可证取决于项目包的使用方式...

用Python下载一个网页保存为本地的HTML文件实例

用Python下载一个网页保存为本地的HTML文件实例

我们可以用Python来将一个网页保存为本地的HTML文件,这需要用到urllib库。 比如我们要下载山东大学新闻网的一个页面,该网页如下: 实现代码如下: import urll...

python基于ID3思想的决策树

这是一个判断海洋生物数据是否是鱼类而构建的基于ID3思想的决策树,供大家参考,具体内容如下 # coding=utf-8 import operator from math imp...

python 第三方库的安装及pip的使用详解

python 第三方库的安装及pip的使用详解

python是一款简单易用的编程语言,特别是其第三方库,能够方便我们快速进入工作,但其第三方库的安装困扰很多人. 现在安装python时,已经能自动安装pip了 安装成功后,我们可以在...