温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2021-07-10 11:25:42 来源:亿速云 阅读:362 作者:小新 栏目:开发技术

这篇文章将为大家详细讲解有关python中如何批量将excel内容进行翻译写入功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

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内容进行翻译写入功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI