首页 > 解决方案 > 尝试基于正则表达式替换 .docx 文件中表中的文本

问题描述

我正在尝试替换Python中.docx文件中表中的文本。我对 Python 还很陌生,所以下面是我稍后将解释的代码:

from typing import List, Any
from docx import Document
import re
import sys


label_name = sys.argv[1:][0]

file_name = "MyDocFile.docx"
doc = Document(file_name)
cell_text_array = []
target_index = 0


def index_cells(doc_obj):
    global cell_text_array
    for table in doc_obj.tables:
        for row in table.rows:
            for cell in row.cells:
                cell_text_array.append(cell.text)


def docx_replace_regex(doc_obj, regex, replace):
    global cell_text_array
    for p in doc_obj.paragraphs:
        if regex.search(p.text):
            inline = p.runs
            # Loop added to work with runs (strings with same style)
            for i in range(len(inline)):
                if regex.search(inline[i].text):
                    text = regex.sub(replace, inline[i].text)
                    inline[i].text = text

    for table in doc_obj.tables:
        for row in table.rows:
            for cell in row.cells:
                docx_replace_regex(cell, regex, replace)


# index the cells in the document
index_cells(doc)


# everything after: /myregex/
target_index = cell_text_array.index('myregex')

# the text that I actually need is 3 spots after 'myregex'
target_index += 3 

former_label = cell_text_array[target_index]

# find regex and replace
regex1 = re.compile(re.escape(r"" + former_label))
replace1 = r"" + label_name
print(regex1)
print(replace1)

# call the replace function and save what has been replaced

docx_replace_regex(doc, regex1, replace1)
doc.save('result1.docx')

第一个函数index_cells()基本上打开MyDocFile.docx并从.docx文件具有的表中搜索每个字符串并将它们保存在 .docx 文件中cell_text_array。我从互联网上获取了下一个函数,因为我通常不使用 Python 编写代码,但在这种情况下我不得不这样做(由于各种原因,我不能使用 Ruby 的 'docx' 模块)。docx_replace_regex()就像它的名字所暗示的那样:打开.docx文件,找到需要替换的文本并将其替换为 replace(即使需要替换的文本在表格或其他段落中找到)。

我要做的基本上是将一个新的名称/标签/标签(无论您想调用什么)作为参数传递给文件,并使用参数从.docx文件中更改旧名称/标签/标签并保存将新编辑的.docx文件复制到另一个新的.docx文件。

如果我要替换的名称/标签/标签没有任何点,则此代码可以正常工作。事实上,我在表格中的其他字符串上对其进行了测试,效果很好。由于这个名称/标签/标签包含我必须使用re.compile(re.escape())的点,所以这些点不会被视为特殊字符,我认为它应该可以工作,但由于某种原因,在生成新文件后,什么都没有改变。

我打印出来regex1replace1查看值。regex1具有以下格式:re.compile('tag\\.name\\.label')whilereplace1只是tag.name.label没有任何''or ""。我认为这可能是不当行为的问题,但我不确定,因为我对 Python 很陌生。

谁能帮我这个?有什么我想念的吗?

标签: pythonregexmoduledocx

解决方案


推荐阅读