使用 Python 生成双语对照译文文件

本代码实现了一个简单的双语对照译文生成器,可以将英文 Word 文件和中文译文 Word 文件按段落匹配,生成一个包含英文和中文段落的双语译文文件。

功能概述:

  • 用户选择英文 Word 文件和中文译文 Word 文件。- 点击“生成”按钮,生成一个新的 Word 文件,包含按段落对照的英文和中文内容。- 代码处理了原文和译文段落数量不匹配的情况,并在生成文件中添加提示信息。

**代码实现:**pythonfrom tkinter import *from tkinter import filedialogimport docx

def open_file(): global eng_file_path eng_file_path = filedialog.askopenfilename(filetypes=[('Word Files', '*.docx')]) eng_file_label.config(text=eng_file_path)

def open_translation_file(): global chi_file_path chi_file_path = filedialog.askopenfilename(filetypes=[('Word Files', '*.docx')]) chi_file_label.config(text=chi_file_path)

def generate_translation(): if not eng_file_path or not chi_file_path: messagebox.showerror('Error', '请先选择英文和中文翻译文件。') return

eng_doc = docx.Document(eng_file_path)    chi_doc = docx.Document(chi_file_path)

eng_paras = [p.text.strip() for p in eng_doc.paragraphs if p.text.strip()]    chi_paras = [p.text.strip() for p in chi_doc.paragraphs if p.text.strip()]

if len(eng_paras) != len(chi_paras):        messagebox.showwarning('Warning', '英文和中文翻译文件段落数量不匹配。')

output_doc = docx.Document()    for i in range(max(len(eng_paras), len(chi_paras))):        eng_para = eng_paras[i] if i < len(eng_paras) else ''        chi_para = chi_paras[i] if i < len(chi_paras) else ''

    output_doc.add_paragraph(eng_para, style='List Bullet')        output_doc.add_paragraph(chi_para, style='List Bullet')

    if i == len(eng_paras):            output_doc.add_paragraph('该段落没有英文翻译。', style='List Bullet')        elif i == len(chi_paras):            output_doc.add_paragraph('该段落没有中文翻译。', style='List Bullet')

output_path = filedialog.asksaveasfilename(defaultextension='.docx')    if output_path:        output_doc.save(output_path)

root = Tk()root.title('双语对照译文生成器')

eng_file_path = ''chi_file_path = ''

eng_file_button = Button(root, text='选择英文文件', command=open_file)eng_file_button.pack(pady=10)

eng_file_label = Label(root, text='')eng_file_label.pack()

chi_file_button = Button(root, text='选择中文翻译文件', command=open_translation_file)chi_file_button.pack(pady=10)

chi_file_label = Label(root, text='')chi_file_label.pack()

generate_button = Button(root, text='生成翻译', command=generate_translation)generate_button.pack(pady=10)

root.mainloop

Python 双语对照译文生成器:实现英文和中文段落匹配

原文地址: https://www.cveoy.top/t/topic/nQPr 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录