Dip*_*pas 4 python docx python-docx
我想用 Python 从 docx 文件中读取标题文本。我正在使用 python-docx 模块。
如果此功能已经实现,有人可以帮助我做到这一点吗?
我尝试这样做,但没有成功。
from docx import Document
document = Document(path)
section = document.sections[0]
print(section.text)
Error:
<class 'AttributeError'>'Section' object has no attribute 'text'
Run Code Online (Sandbox Code Playgroud)
和:
from docx import Document
document = Document(path)
header = document.sections[0].header
print(header.text)
Error:
<class 'AttributeError'>'Section' object has no attribute 'header'
Run Code Online (Sandbox Code Playgroud)
小智 5
当您提出问题时,使用 python-docx 库是不可能的。在0.8.8版本(2019年1月7日)中,添加了页眉/页脚支持。
在 Word 文档中,每个部分都有一个标题。标题有很多潜在的问题(例如,它们可以从一个部分链接到另一个部分,或者在偶数/奇数页上不同),但在简单的情况下,有一个部分和一个不复杂的标题,您只需要浏览节标题中的段落。
from docx import Document
document = Document(path_and_filename)
section = document.sections[0]
header = section.header
for paragraph in header.paragraphs:
print(paragraph.text) # or whatever you have in mind
Run Code Online (Sandbox Code Playgroud)
我正在处理的文档的标题用表格而不是简单的文本布局。在这种情况下,您需要使用rowsinheader.tables[0]而不是段落。