好的,我们可以使用 python-docx 库来处理 DOCX 文件。这个库允许我们读取、修改和创建 Word 文档。
处理文本框(Text Boxes)会稍微复杂一些,因为文本框在 DOCX 结构中可以存在于多个地方(如主文档内容、页眉、页脚),并且可以是“内联形状”(inline shapes)或“浮动形状”(floating shapes)。
下面是一个 Python 脚本,它会尝试找到文档中所有的文本框,并将其内容前后加上 ``` 符号:
from docx import Document
# from docx.enum.shape import WD_SHAPE_TYPE # Not strictly needed if using has_text_frame
def process_text_frame_content(text_frame):
"""
Helper function to process the content of a text_frame.
Adds ``` before and after the existing text.
Returns True if content was modified, False otherwise.
"""
if not text_frame.paragraphs: # Skip if text box is empty
return False
# Collect all text from all paragraphs in the text box
original_text_parts = []
for p in text_frame.paragraphs:
original_text_parts.append(p.text)
full_original_text = "\n".join(original_text_parts)
# Only process if there's actual non-whitespace text
if full_original_text.strip():
modified_text = f"```{full_original_text}```"
# Clear existing paragraphs in the text_frame
# text_frame.clear() # This is simpler but might not always work perfectly with complex formatting
# More robust way to clear:
for p in list(text_frame.paragraphs): # Iterate over a copy
p_element = p._p
p_element.getparent().remove(p_element)
# Add a new paragraph with the modified text
# If modified_text contains newlines, Word will interpret them as paragraph breaks
# when setting .text of a single paragraph.
# If you want to preserve multiple paragraphs within the ```, you'd need to split
# modified_text by \n and add multiple paragraphs.
# However, for ```code block```, usually it's treated as a single block.
new_paragraph = text_frame.add_paragraph()
new_paragraph.text = modified_text
# print(f"Modified text box: {modified_text[:50]}...") # For debugging
return True
return False
def modify_text_boxes_in_docx(input_docx_path, output_docx_path):
"""
Opens a DOCX file, finds all text boxes, adds ``` around their content,
and saves the modified file.
"""
try:
doc = Document(input_docx_path)
except Exception as e:
print(f"Error opening DOCX file '{input_docx_path}': {e}")
return
modified_count = 0
# 1. Process inline shapes in the main document body
# These are shapes embedded within the text flow.
for shape in doc.inline_shapes:
if shape.has_text_frame:
# print(f"Found inline shape with text_frame.")
if process_text_frame_content(shape.text_frame):
modified_count += 1
# 2. Process floating shapes in the main document body
# `doc.shapes` handles "floating" shapes in the main document story (WordProcessingShape).
# Requires python-docx 0.8.7 or newer for `doc.shapes`.
if hasattr(doc, 'shapes'):
for shape in doc.shapes:
if shape.has_text_frame:
# print(f"Found floating shape (doc.shapes) with text_frame: Name '{shape.name}'")
if process_text_frame_content(shape.text_frame):
modified_count += 1
else:
print("Warning: `doc.shapes` attribute not found. Floating shapes in the main body might be missed. "
"Consider upgrading `python-docx`.")
# 3. Process shapes in headers and footers
for section in doc.sections:
# Headers (default, first page, even page)
headers = [section.header, section.first_page_header, section.even_page_header]
for header in headers:
if header:
for shape in header.shapes: # Floating shapes in header
if shape.has_text_frame:
# print(f"Found floating shape in header with text_frame: Name '{shape.name}'")
if process_text_frame_content(shape.text_frame):
modified_count += 1
for shape in header.inline_shapes: # Inline shapes in header
if shape.has_text_frame:
# print(f"Found inline shape in header with text_frame.")
if process_text_frame_content(shape.text_frame):
modified_count += 1
# Footers (default, first page, even page)
footers = [section.footer, section.first_page_footer, section.even_page_footer]
for footer in footers:
if footer:
for shape in footer.shapes: # Floating shapes in footer
if shape.has_text_frame:
# print(f"Found floating shape in footer with text_frame: Name '{shape.name}'")
if process_text_frame_content(shape.text_frame):
modified_count += 1
for shape in footer.inline_shapes: # Inline shapes in footer
if shape.has_text_frame:
# print(f"Found inline shape in footer with text_frame.")
if process_text_frame_content(shape.text_frame):
modified_count += 1
if modified_count > 0:
try:
doc.save(output_docx_path)
print(f"Successfully modified {modified_count} text box(es).")
print(f"Saved modified document to: {output_docx_path}")
except Exception as e:
print(f"Error saving DOCX file '{output_docx_path}': {e}")
else:
print("No text boxes found or no text content to modify in text boxes.")
# Optionally, you might still want to save the document if other changes were made
# or if you want a copy even if no text boxes were modified.
# For this specific task, if no modifications, saving might not be necessary.
# try:
# doc.save(output_docx_path) # Save anyway
# print(f"Saved document (no text boxes modified) to: {output_docx_path}")
# except Exception as e:
# print(f"Error saving DOCX file '{output_docx_path}': {e}")
if __name__ == "__main__":
# --- Configuration ---
input_file = "input.docx" # 修改为你的输入文件名
output_file = "output_with_backticks.docx" # 修改为你的输出文件名
# ---------------------
# Create a dummy input.docx for testing if it doesn't exist
import os
if not os.path.exists(input_file):
try:
print(f"'{input_file}' not found. Creating a dummy file for testing.")
doc_test = Document()
doc_test.add_paragraph("This is a regular paragraph.")
# Add an inline text box (requires more complex XML manipulation or specific methods if available)
# For simplicity, we'll assume text boxes are added via Word UI.
# python-docx doesn't have a direct high-level "add text box" to paragraph.
# Adding floating text boxes is possible but complex.
# The script focuses on MODIFYING existing text boxes.
# Let's add a paragraph and tell the user to manually insert a text box there.
doc_test.add_paragraph("Please manually insert a text box in this document, add some text to it, and save as 'input.docx' before running the script fully.")
# Example of how a text box might be structured internally (very simplified)
# This is more for understanding; direct manipulation is complex.
# For testing, it's best to create a docx with text boxes using MS Word.
# Create a simple text box in a known way that python-docx can access
# (This is a bit of a hack to simulate a text box for testing, might not be a "true" text box in all Word versions)
# A more reliable way is to manually create the test docx.
# However, let's try to add one if possible to demonstrate.
# Adding a "shape" that can act as a text box is complex via python-docx API.
# The script is designed to FIND existing text boxes.
doc_test.save(input_file)
print(f"Dummy '{input_file}' created. Please open it, add some text boxes with content, save it, and then re-run the script.")
except Exception as e:
print(f"Could not create dummy input file: {e}")
else:
print(f"Using existing input file: '{input_file}'")
modify_text_boxes_in_docx(input_file, output_file)
如何使用:
-
安装 python-docx:
pip install python-docx
-
准备 input.docx:
- 将你的 Word 文档命名为
input.docx(或者修改脚本中的 input_file 变量为你文件的实际名称)。
- 确保这个文档中包含你想要修改的文本框。
-
运行脚本:
- 将上面的 Python 代码保存为一个
.py 文件(例如 modify_docx.py)。
- 在终端中运行脚本:
python modify_docx.py
-
检查 output_with_backticks.docx:
- 脚本会生成一个名为
output_with_backticks.docx (或你指定的输出文件名) 的新文件,其中文本框的内容应该已经被修改。
重要说明:
- 文本框的复杂性: DOCX 格式非常复杂。文本框可以有多种类型和嵌入方式。此脚本尝试覆盖常见的情况(内联形状、浮动形状、页眉页脚中的形状)。
doc.shapes: doc.shapes 用于访问文档主体中的浮动形状。这个特性是在 python-docx 0.8.7 版本中添加的。如果你的 python-docx 版本较低,这部分可能无法工作,脚本中有一个警告提示。
- 清空和重写内容:
text_frame.clear() 是一个简单的方法来清空文本框内容,但有时对于复杂的格式可能不够完美。
- 脚本中采用了一个更稳健的方法:迭代删除
text_frame 中的每个段落元素 (p._p)。
- 然后,它将整个修改后的文本(包括原始段落间的换行符)添加为一个新段落。Word 通常会将包含换行符的文本正确地显示为多行。
- 测试: 强烈建议在你的实际文档的副本上测试此脚本,以确保它按预期工作,因为 DOCX 文件的内部结构可能因创建方式和 Word 版本而异。
- 创建测试文件: 如果你没有
input.docx,脚本会尝试创建一个非常基础的 input.docx。但最好的测试文件是你手动用 Word 创建的,包含各种文本框(在正文、页眉、页脚中,有些内联,有些浮动)。
这个脚本应该能处理大多数标准文本框。如果遇到特殊情况,可能需要更深入地研究 python-docx 的底层 XML 操作。