python
import zipfile
import xml.etree.ElementTree as ET
import shutil
import os
from pathlib import Path
def modify_textboxes_in_docx(input_file, output_file):
"""
在docx文件中所有文本框的内容前后添加```符号
"""
# 创建临时目录
temp_dir = Path("temp_docx")
temp_dir.mkdir(exist_ok=True)
try:
# 解压docx文件
with zipfile.ZipFile(input_file, 'r') as zip_ref:
zip_ref.extractall(temp_dir)
# 处理主文档
document_xml = temp_dir / "word" / "document.xml"
if document_xml.exists():
process_xml_file(document_xml)
# 处理页眉
for header_file in (temp_dir / "word").glob("header*.xml"):
process_xml_file(header_file)
# 处理页脚
for footer_file in (temp_dir / "word").glob("footer*.xml"):
process_xml_file(footer_file)
# 重新打包为docx
with zipfile.ZipFile(output_file, 'w', zipfile.ZIP_DEFLATED) as zip_ref:
for root, dirs, files in os.walk(temp_dir):
for file in files:
file_path = Path(root) / file
arcname = str(file_path.relative_to(temp_dir))
zip_ref.write(file_path, arcname)
print(f"处理完成!输出文件:{output_file}")
finally:
# 清理临时目录
shutil.rmtree(temp_dir, ignore_errors=True)
def process_xml_file(xml_file):
"""
处理单个XML文件中的文本框
"""
# 注册命名空间
namespaces = {
'w': 'http://schemas.openxmlformats.org/wordprocessingml/2006/main',
'mc': 'http://schemas.openxmlformats.org/markup-compatibility/2006',
'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'pic': 'http://schemas.openxmlformats.org/drawingml/2006/picture',
'v': 'urn:schemas-microsoft-com:vml',
'w10': 'urn:schemas-microsoft-com:office:word'
}
# 解析XML
tree = ET.parse(xml_file)
root = tree.getroot()
# 为ElementTree注册命名空间
for prefix, uri in namespaces.items():
ET.register_namespace(prefix, uri)
# 查找所有文本框中的文本
# 方法1: 查找txbxContent中的文本
for txbx in root.findall('.//mc:Choice//w:txbxContent', namespaces):
process_textbox_content(txbx, namespaces)
# 方法2: 查找VML文本框
for textbox in root.findall('.//v:textbox', namespaces):
process_vml_textbox(textbox, namespaces)
# 保存修改后的XML
tree.write(xml_file, encoding='UTF-8', xml_declaration=True)
def process_textbox_content(txbx_element, namespaces):
"""
处理txbxContent类型的文本框
"""
for para in txbx_element.findall('.//w:p', namespaces):
# 获取段落中的所有文本
texts = []
for run in para.findall('.//w:r', namespaces):
for text in run.findall('.//w:t', namespaces):
if text.text:
texts.append(text.text)
if texts:
# 清除原有内容
for run in para.findall('.//w:r', namespaces):
para.remove(run)
# 创建新的run并添加修改后的文本
new_run = ET.SubElement(para, '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}r')
new_text = ET.SubElement(new_run, '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}t')
new_text.text = '```' + ''.join(texts) + '```'
def process_vml_textbox(textbox_element, namespaces):
"""
处理VML类型的文本框
"""
for para in textbox_element.findall('.//w:p', namespaces):
texts = []
for run in para.findall('.//w:r', namespaces):
for text in run.findall('.//w:t', namespaces):
if text.text:
texts.append(text.text)
if texts:
# 修改第一个文本节点
first_text = para.find('.//w:t', namespaces)
if first_text is not None:
first_text.text = '```' + ''.join(texts) + '```'
# 删除其他文本节点
for run in para.findall('.//w:r', namespaces)[1:]:
para.remove(run)
# 使用示例
if __name__ == "__main__":
input_docx = "input.docx" # 输入文件名
output_docx = "output_with_backticks.docx" # 输出文件名
modify_textboxes_in_docx(input_docx, output_docx)