【问题标题】:How to extract heading numbers from a document using python-docx?如何使用 python-docx 从文档中提取标题编号?
【发布时间】:2021-01-22 06:52:48
【问题描述】:

我正在使用 python-docx 库从 docx 文档中提取数据,但是我还想要标题编号/段落编号。我想构建一个校对工具,我需要知道这些信息,但是 我在文本中找不到该信息,也找不到段落的样式。有什么方法可以提取这些信息吗? 我可以遍历相同标题编号的标签,但是如果用户在编写文档时没有使用正确的标题标签怎么办? 或者,如果他们选择不使用默认的字词约定 1, 1.1, 1.1.1, a 而是选择使用自己的东西怎么办?

基本上我想要一种方法来提取这些数字,2, 2.1, 2.2.1, (a)。我该怎么做?

【问题讨论】:

    标签: python parsing ms-word python-docx


    【解决方案1】:

    我尝试了一个类似的,但用于多语言。

    首先你必须观察标题(1, 2, 3 ..) 和副标题(2.1, 2.2 ..) 并尝试提取一些常见的东西。它们可能具有以下一些独特的模式:

    1. 粗体字
    2. 字体、大小
    3. 标题以 int(2) 开头,副标题以 float (2.1) 开头
    4. 文本之前和数字之后的分隔符('\t' 或'空格')是什么

    观察这些事情并尝试构建模式。通过使用正则表达式,我们可以提取所需的内容。

    这是正则表达式,它将满足您的情况。即使是多语言。

    headings = regex.search("\d+\.\t(\p{Lu}+([\s]+)?)+")
    subHeadings =regex.search("\d+\.\d+\t\p{Lu}(\p{Ll}+)+")
    

    python 正则表达式 ( re ) 不向后兼容。所以使用这个 [regex][1] 特别是如果你的文本是多语言的。

    import regex
    from docx import Document
    doc = Document("<<Your doc file name here>>")
    
    # Iterate through paragraphs ( in a word everything is a paragraph)
    # Even the blank lines are paragraphs
    for index, para in enumerate(doc.paragraphs):
    
    # Skipping the blank paragraphs
        if(para.text):
            headings = regex.search("\d+\.\t(\p{Lu}+([\s]+)?)+",para.text,regex.UNICODE)
            subHeadings = regex.search("\d+\.\d+\t\p{Lu}(\p{Ll}+)+",para.text,regex.UNICODE)
            if headings:
                if para.runs:
                    for run in para.runs:
                        # At run level checking for bold or italic.
                        if run.bold:
                            print("Bold Heading :",headings.group(0))
                        if run.italic:
                            print("Italic Heading :",headings.group(0))
              if subHeadings :
                if para.runs:
                    for run in para.runs:
                        # At run level checking for bold or italic.
                        if run.bold:
                            print("Bold subHeadings :",subHeadings .group(0))
                        if run.italic:
                            print("Italic subHeadings :",subHeadings .group(0))
    

    注意:粗体或斜体在运行级别并不总是存在。如果你没有得到这些参数,你应该检查样式和参数级别。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多