【问题标题】:Changing paragraph font properties in for-loop changes properties in all paragraphs within said loop在 for 循环中更改段落字体属性会更改所述循环内所有段落的属性
【发布时间】:2021-08-15 07:58:24
【问题描述】:

我正在尝试使用 Python Docx 生成稍后将手动操作的 word 文档。 尝试使用不同的字体样式在下方添加段落标题和空格以进行书写时,出现了我的问题。

我想要的输出看起来像

标题

第一节(新罗马时代)

亚达亚达亚达(在爱丽儿)

第二部分(Times New Roman)

等等

虽然我已经设法创建了部分和中间的断点,但无论哪种字体在我的代码中最后出现,都用于每个部分和断点。 我的目标是让中断处为空,但在写入时,字体样式/大小会自动设置为代码“sections_break”部分中的属性。

from docx import Document
from docx.shared import Inches
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE


document = Document()
heading = document.add_paragraph("Heading")
heading.style = document.styles.add_style('Style Name', WD_STYLE_TYPE.PARAGRAPH)
heading_font = heading.style.font
heading_font.name = 'Times New Roman'
heading_font.size = Pt(12)
heading_font.bold = True
for section in profile_sections:
    sections = document.add_paragraph(section)
    sections_font = sections.style.font
    sections_font.name = 'Palatino Linotype'
    sections_font.size = Pt(11)
    sections_font.bold = True
    sectionbreaks = document.add_paragraph(" ")
    sectionbreaks.name = 'Times New Roman'
    sectionbreaks.size = Pt(11)
    sectionbreaks.bold = False

【问题讨论】:

  • “Section”和“Sections”是 Word vba 中的保留名称。您尚未命名段落样式,并且似乎并未真正将其用作样式。我承认我对 Python 一无所知。

标签: python ms-word python-docx


【解决方案1】:

您正在更改段落样式的字体,而不是段落本身的字体。所有这些段落都共享相同的(默认)样式(很可能是“正常”),因此它们都获得了最终样式。

尝试更改包含您希望具有不同字符格式的文本的运行字体:

paragraph = document.add_paragraph("foobar")
font = paragraph.runs[0].font
font.name = 'Palatino Linotype'
font.size = Pt(11)
font.bold = True

在此处查看段落样式的文档:
https://python-docx.readthedocs.io/en/latest/user/styles-understanding.html
在这里:
https://python-docx.readthedocs.io/en/latest/user/styles-using.html

此文本文档页面可以帮助您了解段落和运行之间的重要区别以及为什么在运行级别应用字体:
https://python-docx.readthedocs.io/en/latest/user/text.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-09-02
    • 2022-06-12
    • 1970-01-01
    • 2014-12-19
    • 1970-01-01
    相关资源
    最近更新 更多