python-pptx替换PPT文本两类报错原因及解决方法
python-pptx 文本替换代码报错修复方案
第一个报错:NameError: name 'List' is not defined
报错原因
函数参数的类型注解使用了List类型,但没有提前导入该类型。Python 3.9版本以前,List属于typing模块下的类型,不是内置关键字,直接使用会触发名称未定义错误。
修复方法
二选一即可:
- 在代码开头添加导入语句:
from typing import List - 如果使用Python 3.9及以上版本,直接把函数注解里的
List换成内置类型list,不需要额外导入。
第二个报错:TypeError: replace_text() missing 1 required positional argument: 'shapes'
报错原因
你定义的replace_text是普通全局函数,但参数列表里多写了一个self参数。self是Python类中实例方法的首个固定参数,普通函数不需要这个参数。你调用函数时只传了translation和shapes两个实参,函数定义要求传入3个位置参数,参数数量不匹配就会抛出缺参错误。
修复方法
删除函数定义里的self参数,修改后的函数声明为:
def replace_text(replacements: dict, shapes: List):
关于文件保存的问题
替换完成后可以直接使用prs.save('output.pptx')保存修改后的文件,这是python-pptx库的标准保存接口,会将内存中所有对PPT的修改写入指定路径的文件。建议不要和原文件用完全相同的路径和文件名,避免覆盖原文件导致无法回滚。
修复后完整可运行代码
from typing import List from pptx import Presentation prs = Presentation('/content/drive/MyDrive/presentation1.pptx') # 提取所有幻灯片中的形状 slides = list(prs.slides) shapes = [] for slide in slides: for shape in slide.shapes: shapes.append(shape) def replace_text(replacements: dict, shapes: List): """接收{匹配原文: 替换译文}格式字典,替换所有匹配文本 暂不支持图表、SmartArt图形内的文本替换 """ for shape in shapes: for match, replacement in replacements.items(): # 处理普通文本框内容 if shape.has_text_frame: if shape.text.find(match) != -1: text_frame = shape.text_frame for paragraph in text_frame.paragraphs: for run in paragraph.runs: run.text = run.text.replace(str(match), str(replacement)) # 处理表格单元格内容 if shape.has_table: for row in shape.table.rows: for cell in row.cells: if match in cell.text: cell.text = cell.text.replace(match, replacement) translation = {' Architecture': 'आर्किटेक्चर', ' Conclusion': 'निष्कर्ष', ' Motivation / Entity Extraction': 'प्रेरणा / इकाई निष्कर्षण', ' Recurrent Deep Neural Networks': 'आवर्तक गहरे तंत्रिका नेटवर्क', ' Results': 'परिणाम', ' Word Embeddings': 'शब्द एम्बेडिंग', 'Agenda': 'कार्यसूची', 'Goals': 'लक्ष्य'} replace_text(translation, shapes) prs.save('output.pptx')
补充说明:现有替换逻辑是按文本块(run)匹配替换,如果待替换的原文因为格式差异(比如部分文字加粗、变色)被拆分到多个run中,会出现匹配失败的情况。如果后续遇到替换不生效的问题,可以调整逻辑直接处理段落级文本,当前给出的翻译条目如果完整存在于单个run中,现有代码可正常运行。
内容的提问来源于stack exchange,提问作者sha25
相关产品推荐
相关产品推荐

