gpt4 book ai didi

python - 无法将单元格内或 pptx 中的某些表格内的文本翻译为其他语言

转载 作者:行者123 更新时间:2023-12-01 09:00:57 26 4
gpt4 key购买 nike

无法将单元格内的文本或 pptx 中的某些表格翻译为德语。然而,幻灯片中的简单文本正在被翻译。

我的输入 pptx 如下所示: enter image description here

获取如下输出:Hello World 等未翻译..

enter image description here

我使用的代码如下:

prs = Presentation('old.pptx')
for slide in prs.slides:
for shape in slide.shapes:
if not shape.has_text_frame:
continue
text_frame = shape.text_frame
text_frame.text=translator.translate(text_frame.text,dest='de').text



prs.save('new.pptx')

可以调整上面的代码,以便可以对所有内部 pptx 进行翻译吗?我可以理解它寻找文本框架,但有机会调整它以使其工作吗?如果我从上面的代码中删除下面的内容将会出现错误...

   if not shape.has_text_frame: 
continue

属性错误:“图片”对象没有属性“text_frame”

我浏览了 python-pptx 文档,发现有 char 、 table 、 pictures 等函数,但无法弄清楚如何将其传递给翻译,以便可以翻译其中的文本..引用链接 - https://python-pptx.readthedocs.io/en/latest/

最佳答案

您将需要单独迭代任何表的单元格,如下所示:

def iter_cells(table):
"""Generate each cell in *table*, left-to-right, top-to-bottom."""
for row in table.rows:
for cell in row.cells:
yield cell

def translate_table(table):
for cell in iter_cells(table):
text_frame = cell.text_frame
text_frame.text = translator.translate(text_frame.text, dest='de').text

for shape in slide.shapes:
if shape.has_table:
translate_table(shape.table)
if not shape.has_text_frame:
continue
...

请注意,表格本身并不是一种形状。相反,它包含在 GraphicFrame 形状中。

关于图片问题,并非所有形状都可以包含文本。图片形状就是其中之一,这就是为什么在尝试访问它没有(也不能)拥有的 TextFrame 对象之前必须跳过它。

关于python - 无法将单元格内或 pptx 中的某些表格内的文本翻译为其他语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52459846/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com