python - 无法将文本翻译成单元格内的其他语言或 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/
解决方案
您将需要分别迭代任何表格的单元格,如下所示:
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
图片形状就是其中之一,这就是为什么在尝试访问它没有(也不能)拥有的对象之前必须跳过它的原因。
推荐阅读
- javascript - 在正则表达式模式验证 JavaScript 中允许逗号后有空格
- javascript - React useCallback with debounce works with old value, how to get actual state value?
- mongodb - 如何调试 mongodb 慢速正则表达式查询?
- android - 无法构建 Android Cordova 项目(Ionic 5)
- javascript - 模块构建失败 - 导入后未找到 ESLint 配置
- powerbi - PowerBI/DAX - 总结组成员
- reactjs - React Native Require 循环被允许警告
- android - 从firebase到recyclerView按升序对日期进行排序
- vim - 如何在 vim/macvim 的命令行下删除多余的空白行?
- python - 根据文件名加载多个文件(使用 AWS Glue)