python-docx 中的页眉和页脚
headers and footers in python-docx
我想阅读 Python 中 docx 文件的页眉和页脚文本。我正在使用 python-docx 模块。
我找到了这个文档 - http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html
但我认为它还没有实现。我还看到 github 中有一个 "feature-headers" 分支用于 python-docx - https://github.com/danmilon/python-docx/tree/feature-headers
似乎这个功能从未进入 master 分支。有人用过这个功能吗?你能帮我看看怎么用吗?
非常感谢。
这个问题有更好的解决办法:
用于提取的方法
使用 MS XML Word 文档
只需使用 zip 模块压缩 word 文档,它会让您访问 xml 格式的 word 文档,然后您可以使用简单的 xml 节点提取文本。
以下是从 docx 文件中提取页眉、页脚和文本数据的工作代码。
try:
from xml.etree.cElementTree import XML
except ImportError:
from xml.etree.ElementTree import XML
import zipfile
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
contentToRead = ["header2.xml", "document.xml", "footer2.xml"]
paragraphs = []
for xmlfile in contentToRead:
xml_content = document.read('word/{}'.format(xmlfile))
tree = XML(xml_content)
for paragraph in tree.getiterator(PARA):
texts = [node.text
for node in paragraph.getiterator(TEXT)
if node.text]
if texts:
textData = ''.join(texts)
if xmlfile == "footer2.xml":
extractedTxt = "Footer : " + textData
elif xmlfile == "header2.xml":
extractedTxt = "Header : " + textData
else:
extractedTxt = textData
paragraphs.append(extractedTxt)
document.close()
return '\n\n'.join(paragraphs)
print(get_docx_text("E:\path_to.docx"))
我想阅读 Python 中 docx 文件的页眉和页脚文本。我正在使用 python-docx 模块。
我找到了这个文档 - http://python-docx.readthedocs.io/en/latest/dev/analysis/features/header.html
但我认为它还没有实现。我还看到 github 中有一个 "feature-headers" 分支用于 python-docx - https://github.com/danmilon/python-docx/tree/feature-headers
似乎这个功能从未进入 master 分支。有人用过这个功能吗?你能帮我看看怎么用吗?
非常感谢。
这个问题有更好的解决办法:
用于提取的方法
使用 MS XML Word 文档
只需使用 zip 模块压缩 word 文档,它会让您访问 xml 格式的 word 文档,然后您可以使用简单的 xml 节点提取文本。
以下是从 docx 文件中提取页眉、页脚和文本数据的工作代码。
try:
from xml.etree.cElementTree import XML
except ImportError:
from xml.etree.ElementTree import XML
import zipfile
WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'
def get_docx_text(path):
"""
Take the path of a docx file as argument, return the text in unicode.
"""
document = zipfile.ZipFile(path)
contentToRead = ["header2.xml", "document.xml", "footer2.xml"]
paragraphs = []
for xmlfile in contentToRead:
xml_content = document.read('word/{}'.format(xmlfile))
tree = XML(xml_content)
for paragraph in tree.getiterator(PARA):
texts = [node.text
for node in paragraph.getiterator(TEXT)
if node.text]
if texts:
textData = ''.join(texts)
if xmlfile == "footer2.xml":
extractedTxt = "Footer : " + textData
elif xmlfile == "header2.xml":
extractedTxt = "Header : " + textData
else:
extractedTxt = textData
paragraphs.append(extractedTxt)
document.close()
return '\n\n'.join(paragraphs)
print(get_docx_text("E:\path_to.docx"))