使用 python-docx 检查特定样式
Checking for particular style using python-docx
from docx import *
document = Document('ABC.docx')
for paragraph in document.paragraphs:
for run in paragraph.runs:
if run.style == 'Strong':
print run.text
这是我用来打开 docx 文件并检查是否有粗体文本的代码,但我没有得到任何结果。如果我删除 if 语句,则打印整个文件时没有任何格式/样式。你能告诉我如何使用 python-docx 识别特定样式的文本,如粗体或斜体吗?
谢谢
尽管 bold 和样式 Strong 在呈现时看起来相同,但它们使用两种不同的机制。第一个直接应用粗体,第二个应用可以包含任何其他数量的字体特征的字符样式。
要识别所有 显示为 粗体的文本,您可能需要同时执行这两项操作。
但是要找到应用了粗体的文本,您可以这样做:
for paragraph in document.paragraphs:
for run in paragraph.runs:
if run.bold:
print run.text
请注意,这可能会漏掉显示为粗体的文本,例如出现在整个段落字体格式为粗体的段落中的文本(例如标题 1)。但我认为这就是您正在寻找的 属性。
要检查 特定样式,您可以使用 name
属性 _ParagraphStyle objects
or _CharacterStyle objects
中可用的 name
属性
示例:
for paragraph in document.paragraphs:
if 'List Paragraph' == paragraph.style.name:
print(paragraph.text)
from docx import *
document = Document('ABC.docx')
for paragraph in document.paragraphs:
for run in paragraph.runs:
if run.style == 'Strong':
print run.text
这是我用来打开 docx 文件并检查是否有粗体文本的代码,但我没有得到任何结果。如果我删除 if 语句,则打印整个文件时没有任何格式/样式。你能告诉我如何使用 python-docx 识别特定样式的文本,如粗体或斜体吗? 谢谢
尽管 bold 和样式 Strong 在呈现时看起来相同,但它们使用两种不同的机制。第一个直接应用粗体,第二个应用可以包含任何其他数量的字体特征的字符样式。
要识别所有 显示为 粗体的文本,您可能需要同时执行这两项操作。
但是要找到应用了粗体的文本,您可以这样做:
for paragraph in document.paragraphs:
for run in paragraph.runs:
if run.bold:
print run.text
请注意,这可能会漏掉显示为粗体的文本,例如出现在整个段落字体格式为粗体的段落中的文本(例如标题 1)。但我认为这就是您正在寻找的 属性。
要检查 特定样式,您可以使用 name
属性 _ParagraphStyle objects
or _CharacterStyle objects
name
属性
示例:
for paragraph in document.paragraphs:
if 'List Paragraph' == paragraph.style.name:
print(paragraph.text)