簡體   English   中英

如何使用python搜索和替換DOTM文件中的字符串

[英]How to search and replace string in DOTM file using python

使用我想在 word DOTM 文件中搜索和替換特定字符串的項目。 然而,在 DOTM 文件中搜索我必須使用 docx2python 但替換搜索到的詞仍然令人頭疼。 可以在 DOTM 文件中進行替換嗎?

docx 文件中的段落由文本runs MS Word 將任意拆分文本運行,通常在一個單詞的中間。

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

這些中斷是由於樣式差異、版本差異、拼寫檢查狀態等造成的。這使得算法搜索和替換等問題成為問題。 我經常使用帶有占位符(例如#CATEGORY_NAME# )的 docx 模板,然后用數據替換這些占位符。 如果您的占位符被分解(例如, #CATEGORY_NAME# ),這將不起作用。

Docx2python v2 將 XML 中的此類運行合並為預處理步驟。 具體來說,Docx2Python 合並運行與 DOCX2PYTHON 看到的格式相同的格式,也就是說,Docx2Python 將忽略版本數據、拼寫檢查狀態等,但尊重支持的格式元素,如粗體、斜體、字體大小等。

使用參數html=False ,Docx2Python 將合並幾乎所有運行(有些像鏈接故意分開)以使大多數段落一次運行。

這些例子應該讓一切都清楚。 查看 Docx2Python utilities.py .py 模塊中的replace_docx_text和其他函數。

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"
        )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM