【问题标题】:How to change to font of a specific paragraph with docx (It's changing the font of the entire word document)如何使用 docx 更改为特定段落的字体(它正在更改整个 word 文档的字体)
【发布时间】:2021-08-16 19:58:13
【问题描述】:

所以我的主要问题是我目前正在尝试使用代码根据我的输入输出求职信。我将更改变量的代码并稍后输入。 我正在使用具有特定字符串的 word 文档模板,我将使用正则表达式对其进行更改。我的主要问题是,当我更改某些内容时,它会返回到原始字体。但是没有什么太大的变化,但我必须加粗 2 个单词并缩小 2 个单词的字体,以便将一些更改的单词返回到原始模板。

当我使用 docx.paragraphs 更改一个特定段落的粗体时,它会更改整篇论文的字体,而不是该特定段落的字体。我使用 document.paragraphs[3].text 来确保它应该只更改我需要的两个单词并且正确显示,但是当我使用 document.paragraphs[3].style.font.bold = True 时,它会更改整个文档的粗体。

from docx import Document
import re

document = Document('Cover_Letter.docx')
for para in  document.paragraphs:
    if 'Buisness_Name' in para.text:
        para.text = re.sub('Buisness_Name', 'NEWBUISNESS', para.text)
    if 'Date_Name' in para.text:
        para.text = re.sub('Date_Name', 'NEWDATE', para.text)
    if 'Internship_Name' in para.text:
        para.text = re.sub('Internship_Name', 'NEWINTERNSHIP', para.text)
    if 'parachange567' in para.text:
        para.text = re.sub('parachange567', 'NEWTEXT', para.text)

document.paragraphs[3].style.font.bold = True
    # print(para.text)
document.save('demo.docx')

【问题讨论】:

    标签: python docx python-docx


    【解决方案1】:

    您是否尝试过创建新样式?

    来自docs

    >>> from docx.enum.style import WD_STYLE_TYPE
    >>> styles = document.styles
    >>> style = styles.add_style('Citation', WD_STYLE_TYPE.PARAGRAPH)
    >>> style.name
    'Citation'
    >>> style.type
    PARAGRAPH (1)
    

    然后将段落样式设置为新样式?

    【讨论】:

      猜你喜欢
      • 2017-07-12
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-02
      • 2015-02-27
      相关资源
      最近更新 更多