阅读Python中的.docx文件以查找删除线、项目符号和其他格式

2024-10-01 09:22:39 发布

您现在位置:Python中文网/ 问答频道 /正文

如果Python文件中出现了一个删除线,那么在docme文件中出现了一个删除线的?我试图编写一个脚本来识别文档中的结构并解析内容。在

到目前为止,我能够阅读一个.docx文件并遍历段落,确定粗体的段落。在

from docx import Document
document = Document(r'C:\stuff\Document.docx')
for p in document.paragraphs:
    print p.text
    for run in p.runs:
        if run.bold:
            print 'BOLD ' + run.text

其余的暂时不见了。在


Tags: 文件runtextin文档脚本内容for
3条回答

根据mkrieger1的建议-我建议使用Pandoc将.docx转换为.html并从那里解析文档。在

安装Pandoc与安装pythondocx是一样的,从.docx到.html的转换就像使用Pandoc的魅力一样。在.html中,我正在解析的文档的结构和所有格式元素都非常清晰,因此很容易使用。在

根据Python DocX Docs,使用本机Word DocX解析器,而不是将其转换为HTML并使用HTML解析器:

from docx.enum.style import WD_STYLE_TYPE
styles = document.styles
paragraph_styles = [
    s for s in styles if s.type == WD_STYLE_TYPE.PARAGRAPH
]
for style in paragraph_styles:
    if style.name == 'List Bullet':
        print "I'm a bullet"

对于删除线,您只需修改示例,如下所示:

from docx import Document
document = Document(r'C:\stuff\Document.docx')
for p in document.paragraphs:
    for run in p.runs:
        if run.font.strike:
            print "STRIKE: " + run.text

请参阅Font对象的API文档,以了解更多有趣的内容。在

相关问题 更多 >