首页 > 解决方案 > python-pptx:从幻灯片中提取文本时出现奇怪的拆分

问题描述

我正在使用https://python-pptx.readthedocs.io/en/latest/user/quickstart.html上的“从演示文稿中的幻灯片中提取所有文本”示例从一些 PowerPoint 幻灯片中提取文本。

from pptx import Presentation

prs = Presentation(path_to_presentation)

# text_runs will be populated with a list of strings,
# one for each text run in presentation
text_runs = []

for slide in prs.slides:
    for shape in slide.shapes:
        if not shape.has_text_frame:
            continue
        for paragraph in shape.text_frame.paragraphs:
            for run in paragraph.runs:
                text_runs.append(run.text)

它似乎工作正常,除了我在一些 text_runs 中出现了奇怪的分裂。我期望将被组合在一起的事物正在被拆分,并且没有我可以检测到的明显模式。例如,有时幻灯片标题分为两部分,有时则不是

我发现我可以通过重新键入幻灯片上的文本来消除奇怪的拆分,但这并不能缩放。

我不能或至少不想将拆分文本的两个部分合并在一起,因为有时文本的第二部分已与不同的文本运行合并。例如,在幻灯片的标题幻灯片上,标题将一分为二,标题的第二部分与标题幻灯片的字幕文本合并。

关于如何消除奇怪/不需要的分裂的任何建议?或者在从 PowerPoint 中读取文本时,这种行为或多或少是意料之中的?

标签: pythonpowerpointpython-pptx

解决方案


我会说这绝对是可以预期的。PowerPoint 会随时拆分运行,可能是为了突出显示拼写错误的单词,或者只是在您暂停输入或修复错字或其他内容时。

关于运行,唯一可以肯定的是它包含的所有字符都共享相同的字符格式。例如,不能保证运行就是所谓的“贪婪”,包括尽可能多的共享相同字符格式的字符。

如果你想重建运行中的“贪婪”一致性,这将取决于你,也许使用这样的算法:

last_run = None
for run in paragraph.runs:
    if last_run is None:
        last_run = run
        continue
    if has_same_formatting(run, last_run):
        last_run = combine_runs(last_run, run)
        continue
    last_run = run

这让您可以实现has_same_formatting()combine_runs(). 这里有一定的优势,因为运行可以包含您不关心的差异,例如脏属性或其他任何内容,您可以选择哪些对您很重要。

实施的开始has_same_formatting()将是:

def has_same_formatting(run, run_2):
    font, font_2 = run.font, run_2.font
    if font.bold != font_2.bold:
        return False
    if font.italic != font_2.italic:
        return False
    # ---same with color, size, type-face, whatever you want---
    return True

combine_runs(base, suffix)看起来像这样:

def combine_runs(base, suffix):
    base.text = base.text + suffix.text
    r_to_remove = suffix._r
    r_to_remove.getparent().remove(r_to_remove)

推荐阅读