Tôi cần phải loại bỏ đầu trang và chân trang trong nhiều tệp docx. Tôi hiện đang thử sử dụng thư viện python-docx, nhưng nó không hỗ trợ đầu trang và chân trang trong tài liệu docx tại thời điểm này (công việc đang tiến hành).Python - Xóa đầu trang và chân trang khỏi tệp docx
Có cách nào để đạt được điều đó trong Python không?
Theo tôi hiểu, docx là định dạng dựa trên xml, nhưng tôi không biết cách sử dụng nó.
P.S.I có một ý tưởng để sử dụng lxml hoặc BeautifulSoup để phân tích xml và thay thế một số bộ phận, nhưng có vẻ bẩn
UPD. Nhờ Shawn, cho một điểm khởi đầu tốt. Tôi đã thực hiện một số thay đổi đối với tập lệnh. Đây là phiên bản cuối cùng của tôi (nó có ích cho tôi, vì tôi cần phải chỉnh sửa nhiều tệp .docx. Tôi đang sử dụng BeautifulSoup, vì trình phân tích cú pháp xml standart không thể nhận được xml-tree hợp lệ. Ngoài ra, tài liệu docx của tôi không có header và footer trong xml. Họ chỉ đặt hình ảnh của header và footer trong một đầu trang. Ngoài ra, cho tốc độ hơn, bạn có thể sử dụng lxml thay vì 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)
vì vậy, đó là nó :) tôi biết, mã không sạch sẽ, xin lỗi vì điều đó.
Cảm ơn bạn! Mã này đã không hoạt động, nhưng sau khi một số refactoring tôi đã được thực hiện nó! Cảm ơn một lần nữa! – drjackild
@drackild, tốt. những gì cần phải được sửa chữa? đăng nó và chia sẻ tất cả :) –