【问题标题】:How to replace latex bold command with Word docx equivalent in python?如何用python中的Word docx等效替换latex粗体命令?
【发布时间】: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-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() 。如果是这样,我不知道该怎么做。一个字符串可能有多个乳胶粗体命令,但大多数字符串不会有任何乳胶命令。

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

编辑:

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

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


    【解决方案1】:

    我想出了如何用re.split 解决我的问题。这仅在乳胶命令是 not 字符串的第一部分时才有效,对于我的情况应该总是如此。但是,这不是最通用的解决方案。

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

    这是结果:

    【讨论】:

      猜你喜欢
      • 2017-09-07
      • 2016-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多