【问题标题】:Parsing docx files in Python在 Python 中解析 docx 文件
【发布时间】:2018-05-24 10:07:28
【问题描述】:

我正在尝试从多个 docx 文件中读取标题。令人讨厌的是,这些标题没有可识别的段落样式。所有段落都有“正常”的段落样式,所以我使用的是正则表达式。标题以粗体显示,结构如下:

A.猫

B.狗

C.猪

D.狐狸

如果文件中的标题超过 26 个,则标题前面会加上“AA.”、“BB.”等

我有以下代码,除了以“D.”开头的任何标题之外,哪种有效,打印两次,例如 [猫、狗、猪、狐、狐]

import os
from docx import Document
import re

directory = input("Copy and paste the location of the files.\n").lower()

for file in os.listdir(directory):

    document = Document(directory+file)

    head1s = []

    for paragraph in document.paragraphs:

        heading = re.match(r'^[A-Z]+[.]\s', paragraph.text)

        for run in paragraph.runs:

            if run.bold:

                if heading:
                    head1 = paragraph.text
                    head1 = head1.split('.')[1]
                    head1s.append(head1)

    print(head1s)

谁能告诉我导致这种情况发生的代码是否有问题?据我所知,Word 文件中这些特定标题的格式或结构并没有什么独特之处。

【问题讨论】:

    标签: python regex python-docx


    【解决方案1】:

    正在发生的事情是循环继续经过 D.Fox,因此在这个新循环中,即使没有匹配项,它也会打印 head1 的最后一个值,即 D.Fox。

    我认为是 for run in paragraph.runs: 以某种方式运行了两次,也许还有第二次“运行”但不可见?

    也许在找到第一个匹配项时添加一个中断足以防止第二次运行触发?

    for file in os.listdir(directory):
    
    document = Document(directory+file)
    
    head1s = []
    
    for paragraph in document.paragraphs:
    
        heading = re.match(r'^[A-Z]+[.]\s', paragraph.text)
    
        for run in paragraph.runs:
    
            if run.bold:
    
                if heading:
                    head1 = paragraph.text
                    head1 = head1.split('.')[1]
                    head1s.append(head1)
                    # this break stops the run loop if a match was found.
                    break
    
    print(head1s)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-07
      • 2011-02-18
      • 2018-02-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多