首页 > 解决方案 > 无法将文本翻译成单元格内的其他语言或 pptx 中的某些表格

问题描述

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

我的输入 pptx 如下所示: 在此处输入图像描述

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

在此处输入图像描述

我正在使用的代码如下:

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

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

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

标签: pythonpython-pptx

解决方案


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

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图片形状就是其中之一,这就是为什么在尝试访问它没有(也不能)拥有的对象之前必须跳过它的原因。


推荐阅读