如何用 python 中等效的 Word docx 替换乳胶粗体命令?

How to replace latex bold command with Word docx equivalent in python?

我正在使用 python 2.7 和 python-docx-template 将信息从文本文件移动到 docx 模板中。文本在放入模板之前被转换为 RichText。

某些文本行可能在文本的某处包含用于粗体的乳胶命令。我正在使用 re.sub() 删除乳胶命令,只留下粗体字。这意味着这个词在最终的 docx 文件中不是粗体。理想情况下,我想用使单词变为粗体所需的 docx 命令替换乳胶命令。

例如,'Here is a sentence with \textbf{bold words} in the middle of it.'

我尝试用 python-docx-templatert.add('bold words', bold=True) 替换乳胶,但是当整个段落都转换为 RichText 时,它不会转换为 RichText。我真的没想到这会奏效,但我还是试过了。

我也尝试添加 xml 命令,<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve"> bold words </w:t></w:r>,但这也没有用。

我怀疑我必须将字符串分成块,然后 rt.add() 将它们放在一起。如果是这样,我不确定该怎么做。一个字符串可能有多个 latex 粗体命令,但大多数字符串不会有任何 latex 命令。

如果需要块,我该怎么做呢?或者,是否有替代解决方案?

编辑:

我能够回答我自己的问题,但我很高兴知道完成此任务的更好或更有效的方法。

from docxtpl import DocxTemplate, RichText
import re

tpl=DocxTemplate('test_tpl.docx')

startsentence = 'Here is a sentence with \textbf{bold words} in the middle of it.'

latexbold = re.compile(r'\textbf\{([a-zA-Z0-9 .]+)\}')

# Strip the latex command.
strippedsentence = re.sub(latexbold, '\1', startsentence)
rtaddsentence = re.sub(latexbold, 'rt.add(" \1 ", bold=True)', startsentence)
docxsentence = re.sub(latexbold, '<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">\1</w:t></w:r>', startsentence)

richstrippedsentence = RichText(strippedsentence)
richrtaddsentence = RichText(rtaddsentence)
richdocxsentence = RichText(docxsentence)

context = {
    'strippedresult': richstrippedsentence,
    'rtresult': richrtaddsentence,
    'docxresult': richdocxsentence,
}

tpl.render(context)
tpl.save('test.docx')

这是 Word 中的结果。

我想出了如何用 re.split 解决我的问题。只有当 latex 命令是 而不是 字符串的第一部分时,这才有效,我的情况应该总是这样。但是,这不是最通用的解决方案。

from docxtpl import DocxTemplate, RichText
import re

tpl=DocxTemplate('test_tpl.docx')

startsentence = 'Here is a sentence with \textbf{bold words} in the middle of it and \textbf{the end of it.}'

latexbold = re.compile(r'\textbf\{([a-zA-Z0-9 .]+)\}')
x = re.split(latexbold, startsentence)
rt = RichText("")
l = len(x)

for i in range(0,l):
    if i%2 == 0:
        rt.add(x[i])
    else:
        rt.add(x[i], bold=True)

context = {
    'example': rt,
}

tpl.render(context)
tpl.save('test.docx')

这是结果: