這是我用來替換 powerpoint 中的文本的代碼。首先,我從 powerpoint 中提取文本,然后將翻譯后的句子和原始句子存盤為字典。
prs = Presentation('/content/drive/MyDrive/presentation1.pptx')
# To get shapes in your slides
slides = [slide for slide in prs.slides]
shapes = []
for slide in slides:
for shape in slide.shapes:
shapes.append(shape)
def replace_text(self, replacements: dict, shapes: List):
"""Takes dict of {match: replacement, ... } and replaces all matches.
Currently not implemented for charts or graphics.
"""
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:
cur_text = run.text
new_text = cur_text.replace(str(match), str(replacement))
run.text = new_text
if shape.has_table:
for row in shape.table.rows:
for cell in row.cells:
if match in cell.text:
new_text = cell.text.replace(match, replacement)
cell.text = new_text
replace_text(translation, shapes)
我收到一個錯誤
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-97-181cdd92ff8c> in <module>()
9 shapes.append(shape)
10
---> 11 def replace_text(self, replacements: dict, shapes: List):
12 """Takes dict of {match: replacement, ... } and replaces all matches.
13 Currently not implemented for charts or graphics.
NameError: name 'List' is not defined
翻譯是一本字典
translation = {' Architecture': '???????????',
' Conclusion': '????????',
' Motivation / Entity Extraction': '??????? / ???? ?????????',
' Recurrent Deep Neural Networks': '?????? ???? ???????? ???????',
' Results': '??????',
' Word Embeddings': '???? ?????????',
'Agenda': '?????????',
'Goals': '??????'}
我可以知道為什么會出現此錯誤。應該采取哪些措施來解決它。我也可以使用保存替換的文本嗎prs.save('output.pptx')
New Error
TypeError Traceback (most recent call last)
<ipython-input-104-957db45f970e> in <module>()
32 cell.text = new_text
33
---> 34 replace_text(translation, shapes)
35
36 prs.save('output.pptx')
TypeError: replace_text() missing 1 required positional argument: 'shapes'
uj5u.com熱心網友回復:
出現“NameError: name 'List' is not defined”的錯誤是因為 'List' 不是 python Typing 中的有效型別。從 Python 3.9 開始,您將需要使用 'list[type]'
例如:
def replace_text(self, replacements: dict, shapes: list[str]):
或者,您可以使用 python 的型別。但是,這在較新的版本中已被棄用。
from typing import List
def replace_text(self, replacements: dict, shapes: List[str]):
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/490272.html
標籤:Python python-3.x 列表 python-pptx
上一篇:在Python中只取矩陣的一部分
