我需要删除许多docx文件中的页眉和页脚。我当前正在尝试使用python-docx库,但此时它不支持docx文档中的页眉和页脚(正在进行中)。Python - 从docx文件中删除页眉和页脚
有没有什么办法可以在Python中实现?
据我所知,docx是一种基于xml的格式,但我不知道如何使用它。
P.S.I有一个主意,用LXML或BeautifulSoup解析XML和更换一些部件,但看起来脏
UPD。感谢肖恩,这是一个很好的起点。我对脚本做了一些修改。这是我的最终版本(对我来说很有用,因为我需要编辑许多.docx文件。我使用BeautifulSoup,因为standart xml解析器无法获得有效的xml树。另外,我的docx文档没有页眉和页脚的XML。他们只是放在头的和页脚的图片在页面的顶部。此外,更多的速度,你可以用它代替汤LXML。
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)
所以,这是它:)我知道,代码不干净,很抱歉。
谢谢!这段代码不起作用,但经过一些重构后,我成功了!再次感谢! – drjackild
@drackild,不错。什么需要纠正?发布它,让我们分享:) –