python多线程 from multiprocessing.dummy import Pool
python操作excel表 import openpyxl
from multiprocessing.dummy import Pool as ThreadPool # 多线程
import openpyxl # excel包
from perplr_fanyi.gtcom import GtCom # 自己的翻译接口
src_path = 'D:\item\item\perplr_fanyi\人-V2.xlsx' # 读表路径
target_path = 'D:\item\item\perplr_fanyi\人-V2_zh.xlsx' # 存表路径(也可以与上一样)
class PerpleTranslate(object):
def __init__(self, con_current):
self.book = openpyxl.load_workbook(src_path) # 获取work book
self.sheet = self.book.active # 获取work表
self.con_current = con_current # 线程数
self.api = GtCom() # 翻译接口
def close(self):
self.book.save(target_path) # 保存文件
def perple(self, i):
for row in range(i, 45732, self.con_current): # 参数1:excel表的行数min 参数2:excel表的行数max 参数3:线程数
if row == 1:
continue
figure_ename = self.sheet.cell(row=row, column=6).value # row为excel表行对应的数,colimn为列对应的数
print(figure_ename) # 单元格的值
try:
name_zh = self.api.translate(figure_ename.strip())
except Exception as e:
name_zh = None
print("error-->:", e)
figure_name_zh = self.sheet.cell(row=row, column=39).value = name_zh # 给单元格赋值
print(figure_name_zh)
print(row)
def parse_rows(self):
try:
pool = ThreadPool(self.con_current)
pool.map(self.perple, range(1, self.con_current+1))
except:
pass
finally:
self.close()
if __name__ == '__main__':
t = PerpleTranslate(100) #100个线程
t.parse_rows()
网友评论