我需要刪除許多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,不錯。什麼需要糾正?發佈它,讓我們分享:) –