我想编写一个程序来抓取我的 docx 文件,遍历它们并根据标题将每个文件拆分为多个单独的文件。在每个 docx 中都有几篇文章,每篇文章下面都有一个“标题 1”和文本。
因此,如果我的原始 file1.docx 有 4 篇文章,我希望将其拆分为 4 个单独的文件,每个文件都有标题和文本。
我到达了它遍历我保存 .docx 文件的路径中的所有文件的部分,我可以分别阅读标题和文本,但我似乎无法找到一种方法合并所有内容并将其拆分为单独的文件,每个文件都有标题和文本。我正在使用 python-docx 库。
import glob
from docx import Document
headings = []
texts = []
def iter_headings(paragraphs):
for paragraph in paragraphs:
if paragraph.style.name.startswith('Heading'):
yield paragraph
def iter_text(paragraphs):
for paragraph in paragraphs:
if paragraph.style.name.startswith('Normal'):
yield paragraph
for name in glob.glob('/*.docx'):
document = Document(name)
for heading in iter_headings(document.paragraphs):
headings.append(heading.text)
for paragraph in iter_text(document.paragraphs):
texts.append(paragraph.text)
print(texts)
如何提取每篇文章的正文和标题?
这是 python-docx 给我的 XML 阅读。红色大括号标记了我要从每个文件中提取的内容。
https://user-images.githubusercontent.com/17858776/51575980-4dcd0200-1eac-11e9-95a8-f643f87b1f40.png
我愿意接受关于如何使用不同方法实现我想要的任何替代建议,或者是否有更简单的方法来使用 PDF 文件。
最佳答案
我认为使用迭代器的方法是一种合理的方法,但我倾向于对它们进行不同的划分。在顶层你可以:
for paragraphs in iterate_document_sections(document.paragraphs):
create_document_from_paragraphs(paragraphs)
然后 iterate_document_sections()
看起来像这样:
def iterate_document_sections(document):
"""Generate a sequence of paragraphs for each headed section in document.
Each generated sequence has a heading paragraph in its first position,
followed by one or more body paragraphs.
"""
paragraphs = [document.paragraphs[0]]
for paragraph in document.paragraphs[1:]:
if is_heading(paragraph):
yield paragraphs
paragraphs = [paragraph]
continue
paragraphs.append(paragraph)
yield paragraphs
像这样的东西与您的其他部分代码相结合应该会给您一些可行的开始。您需要实现 is_heading()
和 create_document_from_paragraphs()
。
请注意,此处的术语“部分”在通用出版用语中用于指代(部分)标题及其从属段落,而不是指 Word 文档部分对象(如 document.sections
)。
关于python - 通过标题将 docx 拆分为 Python 中的单独文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54409495/