【问题标题】:How can I output Word documents/plaintext with all accepted/rejected track changes?如何输出所有接受/拒绝的轨道更改的 Word 文档/纯文本?
【发布时间】:2023-10-13 04:19:01
【问题描述】:

我有一组带有“跟踪更改”功能的文本修改的 .docx 文档。

对于我集中的每个source.docx 文件,我想以编程方式运行两个操作:

  1. 生成两份文档,一份拒绝所有更改,另一份接受所有更改(棘手的步骤)
  2. 转换为纯文本。

换句话说,我想运行以下管道:

source.docx -> sources-all-changes-rejected.docx -> source-all-rejected-plaintext.txt
source.docx -> sources-all-changes-accepted.docx -> source-all-accepted-plaintext.txt

有没有办法做到这一点,例如使用soffice --headless?

我尝试了一个受 Python - Using win32com.client to accept all changes in Word Documents 启发的解决方案。该方法有效,注意使用绝对路径并保存为 txt 文档 https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveformat 。所以我有一个函数,它采用pathlib 路径file_path 并根据需要编写纯文本文档:

def output_track_changed_version(file_path, action):
    
    doc.TrackRevisions = False

    # Delete all comments
    if doc.Comments.Count >= 1:
        doc.DeleteAllComments()

    # Accept/reject all revisions
    doc.Revisions.AcceptAll()
    changed_text = doc.Content.Text
    doc.Undo()
    doc.Revisions.RejectAll()
    original_text = doc.Content.Text

    # [CUT: code to dump changed/original strings to file and then...]

    doc.Close(False, False, False)
    word.Application.Quit()

但我不想坚持使用win32com.client,我更喜欢基于 LibreOffice 的解决方案 + Python,可以在 Linux 虚拟机上轻松设置。

【问题讨论】:

    标签: python ms-word docx libreoffice


    【解决方案1】:

    我不知道,它是否解决了你的问题,但你可以使用 docx 库(使用pip install python-docx 命令安装)来解决这个任务。

    例子:

    import docx
    
    #rejected changes
    doc = docx.Document('source.docx')
    doc.save('sources-all-changes-rejected.docx')
    
    #txt
    r_text = []
    for par in doc.paragraphs:
        r_text.append(par.text)
    r_text = '\n'.join(r_text)
    
    filename = 'source-all-rejected-plaintext.txt'
    with open(filename, 'w') as r_txt:
        r_txt.write(r_text)
    
    #accepted changes
    for par in doc.paragraphs:
        #do changes
        pass
    
    #txt
    a_text = []
    for par in doc.paragraphs:
        a_text.append(par.text)
    a_text = '\n'.join(a_text)
    
    filename = 'source-all-accepted-plaintext.txt'
    with open(filename, 'w') as a_txt:
        a_txt.write(a_text)
    
    #docx
    doc.save('sources-all-changes-accepted.docx')
    

    然后你可以循环遍历集合中的所有文件。

    【讨论】:

    • 嘿,谢谢!一件重要的事情是,# do changes 位中需要发生的事情非常关键:更改已经在源文档中(使用“跟踪更改”功能执行),我需要在此之前拒绝/接受所有更改输出结果。
    最近更新 更多