本文目录导读:
我来为您介绍几个Python处理Word文档的实用案例,主要使用python-docx库。
基础环境准备
pip install python-docx
创建和编辑Word文档
from docx import Document
from docx.shared import Inches, Pt, RGBColor
from docx.enum.text import WD_ALIGN_PARAGRAPH
def create_simple_document():
"""创建简单的Word文档"""
# 创建文档对象
doc = Document()
# 添加标题
doc.add_heading('Python Word处理案例', level=0)
# 添加段落,设置格式
paragraph = doc.add_paragraph()
paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
run = paragraph.add_run('这是一个Python生成的Word文档')
run.font.size = Pt(14)
run.font.color.rgb = RGBColor(0, 128, 0)
run.bold = True
# 添加普通段落
doc.add_paragraph('这是第一段内容')
doc.add_paragraph('这是第二段内容,包含一些文字。')
# 保存文档
doc.save('示例文档.docx')
print("文档创建成功!")
create_simple_document()
读取和修改现有文档
from docx import Document
def read_and_modify_document():
"""读取并修改现有文档"""
try:
# 读取文档
doc = Document('示例文档.docx')
print("=== 文档内容 ===")
# 读取所有段落
for i, paragraph in enumerate(doc.paragraphs):
print(f"段落{i}: {paragraph.text}")
# 修改第一个段落
if doc.paragraphs:
doc.paragraphs[0].text = "修改后的标题"
# 添加新内容
doc.add_paragraph("这是新添加的内容")
# 保存修改
doc.save('修改后的文档.docx')
print("\n文档修改成功!")
except FileNotFoundError:
print("找不到原始文档")
# read_and_modify_document()
表格处理
from docx import Document
from docx.shared import Inches
def create_table_document():
"""创建包含表格的文档"""
doc = Document()
# 添加标题
doc.add_heading('学生成绩表', level=1)
# 创建表格(3行4列)
table = doc.add_table(rows=3, cols=4)
table.style = 'Table Grid' # 设置表格样式
# 填充表头
headers = ['姓名', '语文', '数学', '英语']
for i, header in enumerate(headers):
table.cell(0, i).text = header
# 填充数据
data = [
['张三', '85', '92', '78'],
['李四', '90', '88', '95']
]
for row_idx, row_data in enumerate(data, start=1):
for col_idx, value in enumerate(row_data):
table.cell(row_idx, col_idx).text = value
doc.save('成绩表.docx')
print("表格文档创建成功!")
create_table_document()
图片和格式处理
from docx import Document
from docx.shared import Inches, Pt, Cm
from docx.enum.text import WD_ALIGN_PARAGRAPH
def add_images_and_formatting():
"""添加图片和复杂格式"""
doc = Document()
# 设置页面边距
section = doc.sections[0]
section.top_margin = Cm(2.5)
section.bottom_margin = Cm(2.5)
# 添加格式化段落
p = doc.add_paragraph()
run = p.add_run('格式化文本示例')
run.font.size = Pt(16)
run.font.bold = True
run.font.italic = True
run.font.color.rgb = RGBColor(255, 0, 0)
# 添加不同样式的文本
p2 = doc.add_paragraph()
run1 = p2.add_run('粗体')
run1.bold = True
run2 = p2.add_run(' 和 ')
run3 = p2.add_run('斜体')
run3.italic = True
# 添加列表
doc.add_paragraph('项目一', style='List Bullet')
doc.add_paragraph('项目二', style='List Bullet')
doc.add_paragraph('项目三', style='List Bullet')
# 尝试添加图片(需要确保图片文件存在)
try:
doc.add_picture('example.jpg', width=Inches(4))
except:
print("图片文件不存在,跳过图片添加")
doc.save('格式化文档.docx')
print("格式化文档创建成功!")
# add_images_and_formatting()
批量处理Word文档
import os
from docx import Document
import glob
def batch_process_documents():
"""批量处理Word文档"""
# 指定文件夹路径
folder_path = "./word_files/"
# 创建文件夹(如果不存在)
if not os.path.exists(folder_path):
os.makedirs(folder_path)
print("请将Word文件放入 word_files 文件夹")
return
# 获取所有Word文件
word_files = glob.glob(os.path.join(folder_path, "*.docx"))
if not word_files:
print("未找到Word文档")
return
print(f"找到 {len(word_files)} 个Word文档")
# 批量处理
for file_path in word_files:
try:
doc = Document(file_path)
file_name = os.path.basename(file_path)
# 统计信息
total_paragraphs = len(doc.paragraphs)
total_tables = len(doc.tables)
# 打印文档信息
print(f"\n文件: {file_name}")
print(f" 段落数: {total_paragraphs}")
print(f" 表格数: {total_tables}")
# 查找特定内容
for paragraph in doc.paragraphs:
if "关键词" in paragraph.text:
print(f" 包含'关键词'的段落: {paragraph.text[:50]}...")
except Exception as e:
print(f"处理 {file_path} 时出错: {e}")
# batch_process_documents()
实用的Word工具函数
from docx import Document
from docx.shared import Inches, Pt
import re
class WordProcessor:
"""Word文档处理工具类"""
def __init__(self, file_path):
self.file_path = file_path
self.document = None
self.load_document()
def load_document(self):
"""加载文档"""
try:
self.document = Document(self.file_path)
return True
except:
print(f"无法加载文件: {self.file_path}")
return False
def extract_all_text(self):
"""提取所有文本"""
if not self.document:
return ""
text = []
for paragraph in self.document.paragraphs:
text.append(paragraph.text)
return '\n'.join(text)
def search_text(self, keyword):
"""搜索关键词"""
if not self.document:
return []
results = []
for i, paragraph in enumerate(self.document.paragraphs):
if keyword in paragraph.text:
results.append((i, paragraph.text))
return results
def replace_text(self, old_text, new_text):
"""替换文本"""
if not self.document:
return False
for paragraph in self.document.paragraphs:
if old_text in paragraph.text:
paragraph.text = paragraph.text.replace(old_text, new_text)
# 保存修改
self.document.save(self.file_path)
return True
def add_header(self, text):
"""添加页眉"""
if not self.document:
return
section = self.document.sections[0]
header = section.header
header.paragraphs[0].text = text
def count_words(self):
"""统计字数"""
text = self.extract_all_text()
# 移除标点符号
text = re.sub(r'[^\w\s]', '', text)
words = text.split()
return len(words)
# 使用示例
def word_processor_demo():
# 创建处理对象
processor = WordProcessor('示例文档.docx')
# 提取所有文本
all_text = processor.extract_all_text()
print("文档内容:", all_text[:100] if all_text else "空文档")
# 搜索文本
results = processor.search_text("Python")
print(f"找到 {len(results)} 处匹配")
# 统计字数
word_count = processor.count_words()
print(f"总字数: {word_count}")
# word_processor_demo()
常用操作速查
# 常用的文档操作
doc = Document()
doc.add_heading('标题', level=1) # 添加标题
doc.add_paragraph('段落文本') # 添加段落
doc.add_picture('图片.jpg') # 添加图片
doc.add_table(rows=3, cols=4) # 添加表格
# 保存文档
doc.save('output.docx')
常见问题解决
# 处理中文乱码 doc = Document() doc.styles['Normal'].font.name = '宋体' doc.styles['Normal'].font.size = Pt(12) # 设置段落间距 from docx.shared import Pt paragraph = doc.add_paragraph() paragraph.paragraph_format.space_before = Pt(10) paragraph.paragraph_format.space_after = Pt(10)
这些案例覆盖了Word文档处理的大部分常见需求,您可以根据实际需求选择使用哪个案例,或者组合使用多个案例的功能,如果遇到具体的问题,欢迎继续提问!
标签: Word处理