[Python] 纯文本查看 复制代码
# -*- coding: UTF-8 -*-
from tkinter import filedialog
from tkinter import ttk
from tkinter import *
import getpass
import pptx
import os
import os.path
import win32com
import threading
import win32com.client
from tkinter.messagebox import*
from pptx.enum.text import MSO_AUTO_SIZE
from google_trans_new import google_translator
def plus_text(text_frame):
for paragraph in text_frame.paragraphs:
#对于对象的每个段落
for run in paragraph.runs:
#将字从paragraph.runs里提取出来
try:
run.text += '(' + translator.translate(run.text, lang_src = '%s'%language_list[combox_source.get()], lang_tgt = '%s'%language_list[combox_aim.get()]) + ')'
#翻译,源语言与目标语言调用下拉框结果
except:
None
#字+翻译结果
#逐行翻译
auto_changesize(text_frame)
def auto_changesize(text_frame):
try:
text_frame.auto_size = MSO_AUTO_SIZE.TEXT_TO_FIT_SHAPE
except:
None
def process_ppt(fileopen, filesave):
now_process = 0
total_num = 0
prs = pptx.Presentation(fileopen)
for slide in prs.slides:
#对于ppt的每一页
total_num += len(slide.shapes)
for slide in prs.slides:
#对于ppt的每一页
for shape in slide.shapes:
#对于每一页的每一个对象
if shape.has_text_frame:
#验证是否为非表格
text_frame = shape.text_frame
plus_text(text_frame)
if shape.has_table:
#验证是否为表格
table = shape.table
for cell in table.iter_cells():
text_frame = cell.text_frame
plus_text(text_frame)
now_process += 1
#覆盖进度显示
visual_process.set('翻译进度:' + str(100*now_process/total_num)+'%')
#打印进度
if change_form == True:
os.remove(fileopen)
#删除ppt转pptx的临时文件
else:
None
prs.save(filesave)
#保存文件
showinfo(title="成功!",message="翻译完毕,文件已保存至源文件目录")
def browse_button():
global file_path
global visual_path
if check_pow == True:
filepath = filedialog.askopenfilename(title = '请选择一个PPT文件', initialdir = 'C:/Users/%s/Documents'%getpass.getuser(), filetypes = [(
"Microsoft PowerPoint 演示文稿", ".ppt .pptx")], multiple = False)
#如果计算机上有Microsoft PowerPoint则可以打开ppt文件
else:
filepath = filedialog.askopenfilename(title = '请选择一个PPT文件', initialdir = 'C:/Users/%s/Documents'%getpass.getuser(), filetypes = [(
"Microsoft PowerPoint 演示文稿", ".pptx")], multiple = False)
#若没有则不行
if filepath != '':
file_path = filepath
visual_path.set(filepath)
else:
pass
#可视化当前路径
def translate_button():
if file_path != '':
trans_button['state'] = DISABLED
select_button['state'] = DISABLED
combox_source['state'] = DISABLED
combox_aim['state'] = DISABLED
transread = threading.Thread(target=change_format,args=(file_path,))
visual_process.set('正在启动翻译进程...')
transread.start()
else:
showinfo(title = "错误", message = "请先选择待翻译文件")
def change_format(filepath):
global change_form
if filepath[-1] != 'x':
powerpoint = win32com.client.Dispatch('PowerPoint.Application')
win32com.client.gencache.EnsureDispatch('PowerPoint.Application')
powerpoint.Visible = 1
ppt = powerpoint.Presentations.Open(filepath)
filepath = filepath + 'x'
ppt.SaveAs(filepath)
os.system('TASKKILL /IM POWERPNT.EXE')
#杀死Microsoft PowerPoint进程
change_form = True
#改变格式为pptx,记录布尔值
else:
change_form = False
process_ppt(filepath,filepath[:-5] + '_'+translator.translate('已翻译', lang_src = 'zh-cn', lang_tgt = '%s'%language_list[combox_aim.get()]) + '.pptx')
trans_button['state'] = NORMAL
select_button['state'] = NORMAL
combox_source['state'] = "readonly"
combox_aim['state'] = "readonly"
#传递输入与输出路径
def check_powerpoint():
global check_pow
powerpoint = win32com.client.Dispatch('PowerPoint.Application')
if str(powerpoint) == 'Microsoft PowerPoint':
check_pow = True
#检测Microsoft PowerPoint是否存在于本机,输出布尔值
else:
None
if __name__ == '__main__':
language_list = {'自动检测': 'auto', 'afrikaans': 'af', 'albanian': 'sq', 'amharic': 'am', '阿拉伯语': 'ar', 'armenian': 'hy', 'azerbaijani': 'az', 'basque': 'eu', 'belarusian': 'be', 'bengali': 'bn', 'bosnian': 'bs', 'bulgarian': 'bg', 'catalan': 'ca',
'cebuano': 'ceb', 'chichewa': 'ny', '简体中文': 'zh-cn', '繁体中文': 'zh-tw', 'corsican': 'co', 'croatian': 'hr', 'czech': 'cs', 'danish': 'da', 'dutch': 'nl', '英语': 'en', 'esperanto': 'eo',
'estonian': 'et', 'filipino': 'tl', 'finnish': 'fi', '法语': 'fr', 'frisian': 'fy', 'galician': 'gl', 'georgian': 'ka', '德语': 'de', 'greek': 'el', 'gujarati': 'gu', 'haitian creole': 'ht', 'hausa': 'ha', 'hawaiian': 'haw',
'hebrew': 'he', 'hindi': 'hi', 'hmong': 'hmn', 'hungarian': 'hu', 'icelandic': 'is', 'igbo': 'ig', 'indonesian': 'id', 'irish': 'ga', '意大利语': 'it', '日语': 'ja', 'javanese': 'jw', 'kannada': 'kn',
'kazakh': 'kk', 'khmer': 'km', 'korean': 'ko', 'kurdish (kurmanji)': 'ku', 'kyrgyz': 'ky', 'lao': 'lo', 'latin': 'la', 'latvian': 'lv', 'lithuanian': 'lt', 'luxembourgish': 'lb', 'macedonian': 'mk', 'malagasy': 'mg', 'malay': 'ms',
'malayalam': 'ml', 'maltese': 'mt', 'maori': 'mi', 'marathi': 'mr', 'mongolian': 'mn', 'myanmar (burmese)': 'my', 'nepali': 'ne', 'norwegian': 'no', 'odia': 'or', 'pashto': 'ps', 'persian': 'fa', 'polish': 'pl', 'portuguese': 'pt',
'punjabi': 'pa', 'romanian': 'ro', '俄语': 'ru', 'samoan': 'sm', 'scots gaelic': 'gd', 'serbian': 'sr', 'sesotho': 'st', 'shona': 'sn', 'sindhi': 'sd', 'sinhala': 'si', 'slovak': 'sk', 'slovenian': 'sl', 'somali': 'so',
'西班牙语': 'es', 'sundanese': 'su', 'swahili': 'sw', 'swedish': 'sv', 'tajik': 'tg', 'tamil': 'ta', 'telugu': 'te', 'thai': 'th', 'turkish': 'tr', 'turkmen': 'tk', 'ukrainian': 'uk', 'urdu': 'ur', 'uyghur': 'ug', 'uzbek': 'uz',
'vietnamese': 'vi', 'welsh': 'cy', 'xhosa': 'xh', 'yiddish': 'yi', 'yoruba': 'yo', 'zulu': 'zu'}
file_path = ''
check_pow = False
change_form = False
translator = google_translator() #定义translator
check_powerpoint()
main_screen = Tk() #创建主窗口
main_screen.title('Microsoft Powerpoint自动翻译')
main_screen.geometry("600x80+%d+%d" %((main_screen.winfo_screenwidth()-600)/2, (main_screen.winfo_screenheight()-60)/2.6178)) #主窗口水平方向居中,竖直方向处于屏幕黄金分割位
main_screen.wm_attributes('-topmost', 1) #主窗口置顶
main_screen.resizable(width = False, height = False) #主窗口大小不可变
visual_path = StringVar()
visual_path.set('未选择待翻译文件')
path_lable = Label(master = main_screen, textvariable=visual_path)
path_lable.place(x = 20 , y = 35)
visual_process = StringVar()
process_lable = Label(master = main_screen, textvariable=visual_process)
process_lable.place(x=20,y=55)
source_lable = Label(master = main_screen, text="源语言:")
source_lable.place(x = 160, y = 0)
aim_lable = Label(master = main_screen, text="目标语言:")
aim_lable.place(x = 360, y = 0)
select_button = Button(text = "选择文件", command=browse_button)
select_button.place(x = 20, y = 0)
trans_button = Button(text="翻译", command = translate_button)
trans_button.place(x = 80, y = 0)
source_value = StringVar()
combox_source = ttk.Combobox(main_screen, textvariable = source_value, width = 17)
combox_source["values"] = ('自动检测', '英语', '简体中文', '俄语', '德语', '法语', '日语', '阿拉伯语', '西班牙语', '意大利语', '繁体中文', 'afrikaans', 'albanian', 'amharic', 'armenian', 'azerbaijani', 'basque', 'belarusian', 'bengali',
'bosnian', 'bulgarian', 'catalan', 'cebuano', 'chichewa', 'corsican', 'croatian', 'czech', 'danish', 'dutch', 'esperanto', 'estonian', 'filipino', 'finnish', 'frisian', 'galician', 'georgian', 'greek', 'gujarati', 'haitian creole',
'hausa', 'hawaiian', 'hebrew', 'hindi', 'hmong', 'hungarian', 'icelandic', 'igbo', 'indonesian', 'irish', 'javanese', 'kannada', 'kazakh', 'khmer', 'korean', 'kurdish (kurmanji)', 'kyrgyz', 'lao', 'latin', 'latvian', 'lithuanian',
'luxembourgish', 'macedonian', 'malagasy', 'malay', 'malayalam', 'maltese', 'maori', 'marathi', 'mongolian', 'myanmar (burmese)', 'nepali', 'norwegian', 'odia', 'pashto', 'persian', 'polish', 'portuguese', 'punjabi', 'romanian',
'samoan', 'scots gaelic', 'serbian', 'sesotho', 'shona', 'sindhi', 'sinhala', 'slovak', 'slovenian', 'somali', 'sundanese', 'swahili', 'swedish', 'tajik', 'tamil', 'telugu', 'thai', 'turkish', 'turkmen', 'ukrainian', 'urdu',
'uyghur', 'uzbek', 'vietnamese', 'welsh', 'xhosa', 'yiddish', 'yoruba', 'zulu')
combox_source.current(0) #默认当前值为可选列表第一个
combox_source.place(x=210,y =0)
combox_source.configure(state="readonly") #下拉框只读
aim_value = StringVar()
combox_aim = ttk.Combobox(main_screen, textvariable=aim_value,width=17)
combox_aim["values"] = ('简体中文', '繁体中文', '英语', '俄语', '德语', '法语', '日语', '阿拉伯语', '西班牙语', '意大利语', 'afrikaans', 'albanian', 'amharic', 'armenian', 'azerbaijani', 'basque', 'belarusian', 'bengali', 'bosnian',
'bulgarian', 'catalan', 'cebuano', 'chichewa', 'corsican', 'croatian', 'czech', 'danish', 'dutch', 'esperanto', 'estonian', 'filipino', 'finnish', 'frisian', 'galician', 'georgian', 'greek', 'gujarati', 'haitian creole',
'hausa', 'hawaiian', 'hebrew', 'hindi', 'hmong', 'hungarian', 'icelandic', 'igbo', 'indonesian', 'irish', 'javanese', 'kannada', 'kazakh', 'khmer', 'korean', 'kurdish (kurmanji)', 'kyrgyz', 'lao', 'latin', 'latvian', 'lithuanian',
'luxembourgish', 'macedonian', 'malagasy', 'malay', 'malayalam', 'maltese', 'maori', 'marathi', 'mongolian', 'myanmar (burmese)', 'nepali', 'norwegian', 'odia', 'pashto', 'persian', 'polish', 'portuguese', 'punjabi', 'romanian',
'samoan', 'scots gaelic', 'serbian', 'sesotho', 'shona', 'sindhi', 'sinhala', 'slovak', 'slovenian', 'somali', 'sundanese', 'swahili', 'swedish', 'tajik', 'tamil', 'telugu', 'thai', 'turkish', 'turkmen', 'ukrainian', 'urdu',
'uyghur', 'uzbek', 'vietnamese', 'welsh', 'xhosa', 'yiddish', 'yoruba', 'zulu')
combox_aim.current(0)
combox_aim.place(x=422,y =0)
combox_aim.configure(state="readonly")
mainloop() #启动