+
33
-

python如何批量替换ppt中的文字?

python如何批量替换ppt中的文字?


网友回复

+
30
-

Python批量替换PPT中的文字

在Python中,可以使用python-pptx库来批量替换PPT(PowerPoint)文件中的文字。以下是详细的实现方法:

安装必要库
pip install python-pptx
基本替换方法
from pptx import Presentation

def replace_text_in_ppt(input_path, output_path, replace_dict):
    """
    替换PPT中的文本内容

    :param input_path: 输入PPT文件路径
    :param output_path: 输出PPT文件路径
    :param replace_dict: 替换字典,格式为 {'旧文本': '新文本'}
    """
    prs = Presentation(input_path)

    for slide in prs.slides:
        for shape in slide.shapes:
            if shape.has_text_frame:
                # 处理普通文本框
                for paragraph in shape.text_frame.paragraphs:
                    for run in paragraph.runs:
                        for old_text, new_text in replace_dict.items():
                            if old_text in run.text:
                                run.text = run.text.replace(old_text, new_text)
            elif shape.has_table:
                # 处理表格中的文本
                for row in shape.table.rows:
                    for cell in row.cells:
                        for paragraph in cell.text_frame.paragraphs:
                            for run in paragraph.runs:
                                for old_text, new_text in replace_dict.items():
                                    if old_text in run.text:
                                        run.text = run.text.replace(old_text, new_text)

    prs.save(output_path)
    print(f"文件已保存到: {output_path}")

# 使用示例
replace_dict = {
    "旧文本1": "新文本1",
    "旧文本2": "新文本2",
    "{日期}": "2023-11-15"
}

replace_text_in_ppt("input.pptx", "output.pptx", replace_dict)
高级功能扩展1. 批量处理多个PPT文件
import os
from pptx import Presentation

def batch_replace_ppt(folder_path, output_folder, replace_dict):
    """
    批量处理文件夹中的所有PPT文件

    :param folder_path: 包含PPT文件的文件夹路径
    :param output_folder: 输出文件夹路径
    :param replace_dict: 替换字典
    """
    if not os.path.exists(output_folder):
        os.makedirs(output_folder)

    for filename in os.l...

点击查看剩余70%

我知道答案,我要回答