python-docx,获取段落字体大小

问题描述 投票:0回答:2

我想使用 python-docx 访问具有唯一字体或字体大小的段落或运行。我如何获取具有指定字体或字体大小的运行或段落的文本?

python ms-word docx python-docx
2个回答
6
投票

对于任何想知道的人:

for paragraph in doc.paragraphs:
    for run in paragraph.runs:
        if run.font.size == Pt(16):
            print(paragraph.text)

0
投票
# Import the docx module
import docx

# Specify the path to the Word document
path = 'sample.docx'  # Document path

# Open the Word document
doc = docx.Document(path)

# Initialize an empty list to store font sizes
font_sizes = []

# Iterate over each paragraph in the document
for paragraph in doc.paragraphs:
    # Iterate over each run (text with the same formatting) within the paragraph.
    for run in paragraph.runs:
        # Retrieve the font size of the run and append it to the font_sizes list
        font_size = run.font.size.pt
        font_sizes.append(font_size)

# Print the font sizes used in the document
print("Font Sizes used:", font_sizes)
© www.soinside.com 2019 - 2024. All rights reserved.