我需要删除许多 docx 文件中的页眉和页脚。我目前正在尝试使用 python-docx 库,但目前它不支持 docx 文档中的页眉和页脚(正在进行中)。
有没有办法在 Python 中实现这一点?
据我了解,docx 是一种基于 xml 的格式,但我不知道如何使用它。
PSI有个想法用lxml或者BeautifulSoup来解析xml并替换一些部分,但是看起来很脏
UPD。感谢肖恩,一个好的起点。我对脚本进行了一些更改。这是我的最终版本(它对我很有用,因为我需要编辑许多 .docx 文件。我正在使用 BeautifulSoup,因为标准 xml 解析器无法获得有效的 xml-tree。另外,我的 docx 文档没有xml 中的页眉和页脚。他们只是将页眉和页脚的图像放在页面顶部。此外,为了提高速度,您可以使用 lxml 代替 Soup。
import zipfile
import shutil as su
import os
import tempfile
from bs4 import BeautifulSoup
def get_xml_from_docx(docx_filename):
"""
Return content of document.xml file inside docx document
"""
with zipfile.ZipFile(docx_filename) as zf:
xml_info = zf.read('word/document.xml')
return xml_info
def write_and_close_docx(self, edited_xml, output_filename):
""" Create a temp directory, expand the original docx zip.
Write the modified xml to word/document.xml
Zip it up as the new docx
"""
tmp_dir = tempfile.mkdtemp()
with zipfile.ZipFile(self) as zf:
zf.extractall(tmp_dir)
with open(os.path.join(tmp_dir, 'word/document.xml'), 'w') as f:
f.write(str(edited_xml))
# Get a list of all the files in the original docx zipfile
filenames = zf.namelist()
# Now, create the new zip file and add all the filex into the archive
zip_copy_filename = output_filename
docx = zipfile.ZipFile(zip_copy_filename, "w")
for filename in filenames:
docx.write(os.path.join(tmp_dir, filename), filename)
# Clean up the temp dir
su.rmtree(tmp_dir)
if __name__ == '__main__':
directory = 'your_directory/'
files = os.listdir(directory)
for file in files:
if file.endswith('.docx'):
word_doc = directory + file
new_word_doc = 'edited/' + file.rstrip('.docx') + '-edited.docx'
tree = get_xml_from_docx(word_doc)
soup = BeautifulSoup(tree, 'xml')
shapes = soup.find_all('shape')
for shape in shapes:
if 'margin-left:0pt' in shape.get('style'):
shape.parent.decompose()
write_and_close_docx(word_doc, soup, new_word_doc)
所以,就是这样:) 我知道,代码不干净,很抱歉。