python批量将excel内容进行翻译写入功能
由于小编初来乍到,有很多地方不是很到位,还请见谅,但是很实用的哦!
1.首先是需要进行文件的读写操作,需要获取文件路径,方式使用os.listdir(路径)进行批量查找文件。
file_path=‘/home/xx/xx/xx'
#ret返回一个列表
ret=list_dir=os.listdir(file_path)
#遍历列表,获取需要的结尾文件(只考虑获取文件,不考虑执行效率)
foriinret:
ifi.endswith('xlsx'):
#执行的逻辑
2.改写一下我调用的翻译接口
defbaidu_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)#打印结果
returndst
exceptExceptionase:
print(e)
finally:
ifhttpClient:
httpClient.close()
3.现在需要进行读取excel的内容,使用方法,xlrd,小编使用的翻译是借用的百度翻译的API,获取excel内容,传递给API
importhashlib
importhttp.client
importjson
importos
importrandom
importtime
importurllib
importopenpyxl
importxlrd
#借用上边所述的文件路径操作
#appid:翻译API提供,需要注册获取
#secretKey:翻译API提供,需要注册获取
defread_excel(file_path,appid,secretKey):
list_dir=os.listdir(file_path)
foriinlist_dir:
ifi.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
fornuminrange(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)
exceptExceptionase:
print(e)
continue
4.因为上一步调用了这个写入excel的函数,所有我们需要写一个函数来完成写入的操作。
defwrite_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内容进行翻译写入功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!