使用 python 从 MS word docx 文件逐页提取文本

Extraction of text page by page from MS word docx file using python

我有一个 MS docx 文件,我需要从中逐页提取文本。 我试过 python-docx 但它可以提取整个文本但不能按页提取。 我还将我的 docx 转换为 pdf,然后尝试提取文本。问题是,转换后 docx 的页面结构发生了变化。比如转换时,字体大小变了,docx一页的文字内容占了pdf的一页以上。

我一直在寻找一个稳定的解决方案,可以从 docx 中提取分页文本(不转换为 pdf 对我的整个解决方案来说会更好)。有人可以帮我解决这个问题吗?

试试这个


from docx import Document

document = Document('anydoccumnet.docx')
for para in document.paragraphs:
    print(para.text)

在我看来,docx 格式(因此 python docx 库)仅支持段落和部分。

Microsoft Word does not support the concept of hard pages. Instead, when the exported document is opened in Word, Word repaginates it again based on the page size. (source)

所以实际上分页并没有存储在docx文件中,而是由渲染引擎执行的:

DOCX files contain no information about pagination. You won’t find the number of pages in the document unless you calculate how much space you need for each line to ascertain the number of pages. (source)

This page有更多的背景,如果必须保留分页,建议使用PDF。

我发现 Tika 库在读取文件时有一个 xml 内容解析。我用它来捕获 xml 格式并使用正则表达式来捕获它。在对我有用的 python 代码下面写下。

raw_xml = parser.from_file(file, xmlContent=True)
body = raw_xml['content'].split('<body>')[1].split('</body>')[0]
body_without_tag = body.replace("<p>", "").replace("</p>", "").replace("<div>", "").replace("</div>","").replace("<p />","")
text_pages = body_without_tag.split("""<div class="page">""")[1:]
num_pages = len(text_pages)
if num_pages==int(raw_xml['metadata']['xmpTPg:NPages']) : #check if it worked correctly
     return text_pages

我最近遇到了类似的情况。以下使用 docx2python 对我有用:

from docx2python import docx2python
doc_result = docx2python('page-wise-file.docx')
count = 0
para = 0
pages= []
while para < len(doc_result.body[0][0][0]):
    if doc_result.body[0][0][0][para] != "":
        current_page = {}
        current_page_paras = []
        count+=1
        while doc_result.body[0][0][0][para]!= "" and para<len(doc_result.body[0][0][0]):
            current_page_paras.append(doc_result.body[0][0][0][para])
            para+=1
        current_page["page_text"] = "\n".join(current_page_paras)
        current_page["page_no"] = count
        pages.append(current_page)
    else:
        para+=1

尽管这会导致丢失任何格式信息或文本中的任何其他元数据,但如果提取文本是唯一目的,那么这应该可行。

因为 Gerd mentioned, converting the file to PDF and then processing it can also help since libraries like PyPDF2 允许您阅读单独的页面,例如:

from PyPDF2 import PdfFileReader
pdf = PdfFileReader(open("page-wise-file.pdf", "rb"))
page = pdf.getPage(0)
page.extractText()
import win32com.client
import comtypes.client
import pdfplumber
word = win32com.client.Dispatch('Word.Application')
wdFormatPDF = 17
in_file = Filepath
out_file = "out.pdf"
word = comtypes.client.CreateObject('Word.Application')
doc = word.Documents.Open(in_file)
doc.SaveAs(out_file, FileFormat=wdFormatPDF)
doc.Close()
word.Quit()
with pdfplumber.open(out_file) as pdf:       
    for page in pdf.pages:
        out=page.extract_text()            
        print(out)

    
        

据我所知,用 win32com 保存 pdf 文件是一个 1:1 fork