【问题标题】:Read doc/docx content in python while conserving the font style在保存字体样式的同时读取 python 中的 doc/docx 内容
【发布时间】:2021-09-27 08:55:43
【问题描述】:

我想使用每个单词的字体样式读取 doc 文件 test.docx 的内容。它包含以下示例段落。

............

这是一个 test 文件,包含 BoldItalic 内容。我正在写这个作为测试手稿。我所需要的只是在 Python 中阅读每个单词时找到它的 style

......

我正在使用 python-docx 阅读它

from docx import Document

filename = "./test.docx"

document = Document(filename)
for para in document.paragraphs:
    print(para.text)

但它正在阅读没有字体样式的内容(即粗体不再是粗体,斜体不再是斜体)。

有没有办法读取每个单词的字体样式?

【问题讨论】:

    标签: python python-3.x docx python-docx doc


    【解决方案1】:

    您需要解决两个主题来解决此要求:

    1. 如何在终端打印粗体或斜体文字?

    如果你的终端支持它(Windows cmd 不是这种情况,但它可以在 PyCharm Python 控制台中工作)你可以使用 ansi 转义码来做到这一点:

    class FontStyles:
        BOLD = '\033[1m'
        END = '\033[0m'
        ITALIC = '\x1B[3m'
    
    1. 如何获取段落字体样式?

    此信息存储在样式ParagraphStyle 属性的font 属性中。

    总而言之:

    for paragraph in document.paragraphs:
        is_bold = paragraph.style.font.bold
        is_italic = paragraph.style.font.italic
        print(f"{FontStyles.ITALIC if is_italic else ''}{FontStyles.BOLD if is_bold else ''}{FontStyles.END if is_bold or is_italic else ''}")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-10
      • 1970-01-01
      • 2021-06-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多