【问题标题】:Python docx replace string in paragraph while keeping style with a periodPython docx 替换段落中的字符串,同时用句点保持样式
【发布时间】:2021-06-20 14:23:27
【问题描述】:

我在使用 Python Docx 替换字符串同时保持样式 (even with this super useful post) 时遇到问题。我要添加的转折是我的文本中有句点,它们被识别为单独的运行。

我刚开始使用 python-docx,阅读文档后,我的理解是它确实适用于整个段落。我已经尝试在运行级别使用它,但它似乎在句点 [.]、任何数字文本或其他格式的文本处结束。我想要实现的是查找 --> 替换 {{%cellbg key.value }}(如下例所示),同时仍保持样式。

在我的 Word 模板中:

sometext.here{{%cellbg key.value }}some.other.text.i.don't.care.about

我的python代码:

from docx import Document
doc = Document(filename)
for p in doc.paragraphs:
    if re.search('(.*?){{%cellbg (.*?) }}(.*?)', paragraph.text):
        cellbg_og = re.search(r'\{\{%cellbg (.*?)\}\}(.*?)', paragraph.text).group(0)
        cellbg_tag = re.search(r'\{\{\%(.*?)\s\}\}', cellbg_og).group(1)
        replace_cellbg = '{% ' + cellbg_tag + ' %}'
        paragraph.text = paragraph.text.replace(cellbg_og, replace_cellbg)
# doc.save(filename)
doc.save('test.docx')
return 1

理想情况下,当我实现它时,我想要以下结果:

原始模板:sometext.here{{%cellbg key.value }}some.other.text.i.don't.care.about

预期输出:sometext.here{% cellbg key.value %}some.other.text.i.don't.care.about

我目前得到的: sometext.here{% cellbg key.value %}some.other.text.i.don't.care.about

我做错了什么?任何帮助将不胜感激!

【问题讨论】:

  • 答案成功了吗?

标签: python regex docx


【解决方案1】:

您可以将单个模式与捕获组一起使用。

(看代码,我觉得应该是for paragraph in doc.paragraphs:

{{%(cellbg\s+.+?)\s*}}

模式匹配:

  • {{% 字面匹配
  • (捕获group 1(在示例代码中引用\1
    • cellbg\s+.+? 匹配 cellbg,1+ whitspace 字符和 1+ 次任何字符尽可能少(非贪婪)
  • )关闭第一组
  • \s* 匹配可选的空白字符
  • }} 字面上匹配

在替换中使用捕获组,在单个卷曲之间左右自定义间距

{% \1 %}

Regex demo

使用示例字符串的示例:

import re

regex = r"{{%(cellbg\s+.+?)\s*}}"
s = "sometext.here{{%cellbg key.value }}some.other.text.i.don't.care.about"
result = re.sub(regex, r"{% \1 %}", s)

if result:
    print(result)

输出

sometext.here{% cellbg key.value %}some.other.text.i.don't.care.about

【讨论】:

  • 非常感谢!我意识到我还有另一个问题,因为我发布的文本实际上需要在表格中。我知道我应该添加: for table in tpl.tables: for row in table.rows: for cell in row.cells: 但是,现在它对我不起作用...
猜你喜欢
  • 1970-01-01
  • 2018-11-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多