首页 > 解决方案 > 如何使用python搜索和替换DOTM文件中的字符串

问题描述

使用我想在 word DOTM 文件中搜索和替换特定字符串的项目。然而,在 DOTM 文件中搜索我必须使用 docx2python,但替换搜索的单词仍然令人头疼。可以在 DOTM 文件中进行替换吗?

标签: pythonreplaceword

解决方案


docx 文件中的段落由 text 组成runs。MS Word 会任意拆分文本,通常在单词中间。

<w:r>
    <w:t>work to im</w:t>
</w:r>
<w:r>
    <w:t>prove docx2python</w:t>
</w:r>

这些中断是由于样式差异、版本差异、拼写检查状态等造成的。这使得算法搜索和替换等问题成为问题。我经常使用带有占位符(例如,)的 docx 模板,#CATEGORY_NAME#然后用数据替换这些占位符。#CAT如果您的占位符被分解(例如,、、、 ) E,这将不起作用GORY_NAME#

Docx2python v2 将 XML 中的此类运行合并为预处理步骤。具体来说,Docx2Python 以与 DOCX2PYTHON 看到的格式相同的格式运行,也就是说,Docx2Python 将忽略版本数据、拼写检查状态等,但尊重支持的格式元素,如粗体、斜体、字体大小等。

使用 argument html=False,Docx2Python 将合并几乎所有的运行(一些像链接是故意分开的)以使大多数段落运行一次。

这些例子应该让一切都清楚。replace_docx_textDocx2Pythonutilities.py模块中的签出和其他功能。

from docx2python.main import docx2python
from docx2python.utilities import get_links, replace_docx_text, get_headings


class TestSearchReplace:
    def test_search_and_replace(self) -> None:
        """Apples -> Pears, Pears -> Apples

        Ignore html differences when html is False"""
        html = False
        input_filename = "apples_and_pears.docx"
        output_filename = "pears_and_apples.docx"
        assert docx2python(input_filename, html=html).text == (
            "Apples and Pears\n\nPears and Apples\n\n"
            "Apples and Pears\n\nPears and Apples"
        )
        replace_docx_text(
            input_filename,
            output_filename,
            ("Apples", "Bananas"),
            ("Pears", "Apples"),
            ("Bananas", "Pears"),
            html=html,
        )
        assert docx2python(output_filename, html=html).text == (
            "Pears and Apples\n\nApples and Pears\n\n"
            "Pears and Apples\n\nApples and Pears"
        )

    def test_search_and_replace_html(self) -> None:
        """Apples -> Pears, Pears -> Apples

        Exchange strings when formatting is consistent across the string. Leave
        alone otherwise.
        """
        html = True
        input_filename = "apples_and_pears.docx"
        output_filename = "pears_and_apples.docx"
        assert docx2python(input_filename, html=html).text == (
            "Apples and Pears\n\n"
            "Pears and Apples\n\n"
            'Apples and <span style="background-color:green">Pears</span>\n\n'
            "Pe<b>a</b>rs and Apples"
        )
        replace_docx_text(
            input_filename,
            output_filename,
            ("Apples", "Bananas"),
            ("Pears", "Apples"),
            ("Bananas", "Pears"),
            html=html,
        )
        assert docx2python(output_filename, html=html).text == (
            "Pears and Apples\n\n"
            "Apples and Pears\n\n"
            'Pears and <span style="background-color:green">Apples</span>\n\n'
            "Pe<b>a</b>rs and Pears"
        )

推荐阅读