【发布时间】:2015-11-28 16:17:20
【问题描述】:
我正在使用 python 2.7 和 python-docx-template 将信息从文本文件移动到 docx 模板中。文本在放入模板之前转换为 RichText。
某些文本行可能在文本中的某处包含用于加粗的 Latex 命令。我正在使用 re.sub() 删除乳胶命令,只留下粗体字。这意味着这个词在最终的 docx 文件中不是粗体。理想情况下,我想用使单词加粗所需的 docx 命令替换 latex 命令。
例如,'这是一个中间有 \textbf{bold words} 的句子。'
我尝试用python-docx-template 的rt.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() 。如果是这样,我不知道该怎么做。一个字符串可能有多个乳胶粗体命令,但大多数字符串不会有任何乳胶命令。
如果需要分块,我该怎么做?或者,是否有替代解决方案?
编辑:
我能够回答我自己的问题,但我很高兴知道更好或更有效的方法来完成这项任务。
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 中的结果。
【问题讨论】:
标签: python regex python-2.7 python-docx