嗯, 我是一个暖心肠的人, 还是个程序员, 虽然妹子也是一个程序猿, 但是术业有专攻这句话可不是白说的, 妹子做数据分析的, 获取了大概 6000 多个分类单词, 需要一点一点的翻译, 大概一上午的时间吧, 也就翻译了一千左右单词, 这个效率太慢了. 既耽误跟我聊天, 还会容易因为我跟他聊天耽误工作, 这样到头来怎么说也捞不到我的好啊, 然后我就研究了一下, 要不试试调用百度翻译或者是有道翻译的接口试试? 然后, 我就默默的来开始了查翻译的 API, 由于词汇量不多, 所以调用了一下百度的, 当然要是很多的话, 百度是会收费的. 嗯....... 好了, 上代码!
- #python3.6.5
- # coding=utf-8
- #Strong by 20180810
- from hashlib import md5
- from urllib import request
- import random
- import xlrd
- import JSON
- def fanyi(mes):
- appid = '' # 你的 appid
- secretKey = '' # 你的密钥
- httpClient = None
- myurl = 'http://api.fanyi.baidu.com/api/trans/vip/translate' #API 接口
- q = mes.replace("","").replace("&", "") #去除 url 中不符合的字符
- print(q) #打印需要翻译的单词
- fromLang = 'en' #英语
- toLang = 'zh' #中文
- salt = random.randint(32768, 65536) #生成随机数
- sign = (appid + q + str(salt) + secretKey) #密钥
- m1 = md5() #创建 hash5
- m1.update(sign.encode("utf-8"))
- sign = m1.hexdigest() #生成加密字符串
- myurl2 = myurl + '?appid=' + appid + '&q=' + q + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(
- salt) + '&sign=' + sign
- # print(myurl2.replace("",""))
- req = request.Request(myurl2)# 请求接口
- try:
- s = request.urlopen(req) #请求接口
- except Exception as e:
- print(e)
- return {"src": mes, "dst": mes}
- m = s.read().decode("utf-8")
- JS = eval(m)
- #生成字典
- print(JS)
- trans_result = JS["trans_result"]
- #取值
- l = str(trans_result).strip("[").strip("]")
- #洗数据
- a = eval(l)
- #生成字典
- return a #返回
- def read():
- file_path = r'I:\1.xls' #读取文件路径
- # 读取的文件路径
- # file_path = file_path.decode('ANSI')
- # 文件中的中文转码
- data = xlrd.open_workbook(file_path)
- #打开 Excel 文件 获取数据
- table = data.sheet_by_name('Sheet1')
- # 获取 sheet
- nrows = table.nrows
- # 获取总行数
- ncols = table.ncols
- # 获取总列数
- f = open("D:/fanyi.xls", "w")
- #将翻译好的数据写入这个文件
- er = open("D:/fanyicuowu.xls", "w")
- #遇到错误写道这个文件里面
- print("行数", nrows)
- print("列数", ncols)
- for i in range(2, nrows, 1):
- for j in range(0, 4, 1):
- # print("i",i,"j",j)
- cell_value = table.cell(i, j).value
- #去除单元格的值
- # print(cell_value)
- if cell_value == "":
- pass
- # print("kkkkkkk")
- # break
- else:
- print("i",i,"j",j,cell_value)
- a = fanyi(cell_value) #翻译
- try:
- f.write(a["src"] + "\t")
- #写入文件
- f.write(a["dst"] + "\n")
- #写入文件
- except Exception as u:
- print(u)
- er.write(u + "\t")
- #将错误写入文件
- er.write(cell_value + "\n")
- #写入出错的单词
- er.close()
- f.close()
- return None
- if __name__ == '__main__':
- read()
用了大概两个小时时间, 成功解决他需要两天左右时间要完成的工作量.
虽然有可能撩不到, 但是自己也学习了呀, 是不是, 敲代码是最重要的, 作为一个程序员, 怎么可能不敲代码? so, 这是一个动力, 说不定哪天妹子就被撩到了呢.
来源: https://juejin.im/entry/5bf2cebcf265da6151145aca