概述
日常的开发中,有需要解析文档的内容存在,需要进行对文档的结构化解析,然后提供给AI进行解读
实践步骤
1、安装库
pip install python-docx
2、编写代码
import os
import docx
from docx import Document
import xml.etree.ElementTree as ET
# 命名空间配置
nsmap = {
'wp': 'http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing',
'a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'r': 'http://schemas.openxmlformats.org/officeDocument/2006/relationships'
}
# 图片类型映射
content_type_to_ext = {
'image/png': 'png',
'image/jpeg': 'jpg',
'image/jpe': 'jpg',
'image/gif': 'gif',
'image/bmp': 'bmp',
'image/tiff': 'tiff',
'image/x-png': 'png',
'image/pjpeg': 'jpg'
}
def extract_images_from_run(run, img_dir, img_counter):
"""从Run元素中提取图片"""
images = []
try:
xml_str = run._element.xml
root = ET.fromstring(xml_str)
# 查找所有图片元素
for blip in root.findall('.//a:blip', nsmap):
embed = blip.attrib.get(f'{{{nsmap["r"]}}}embed')
if embed and embed in run.part.related_parts:
image_part = run.part.related_parts[embed]
image_data = image_part.blob
# 获取图片扩展名
ext = content_type_to_ext.get(image_part.content_type, 'png')
img_counter += 1
img_name = f'image{img_counter}.{ext}'
img_path = os.path.join(img_dir, img_name)
# 保存图片
with open(img_path, 'wb') as f:
f.write(image_data)
images.append(img_path)
except Exception as e:
print(f"提取图片时出错: {e}")
return images, img_counter
def parse_docx(file_path, img_dir='output_images'):
"""解析Word文档并按顺序返回内容和图片"""
os.makedirs(img_dir, exist_ok=True)
doc = Document(file_path)
result = []
img_counter = 0
# 遍历文档中的所有元素
for element in doc.element.body:
# 处理段落
if element.tag.endswith('p'):
paragraph = docx.text.paragraph.Paragraph(element, doc)
current_text = []
for run in paragraph.runs:
# 收集文本
if run.text.strip():
current_text.append(run.text)
# 提取图片
images, img_counter = extract_images_from_run(run, img_dir, img_counter)
for img_path in images:
# 先保存已收集的文本
if current_text:
result.append({'type': 'text', 'content': ''.join(current_text)})
current_text = []
# 添加图片记录
result.append({'type': 'image', 'path': img_path})
# 处理剩余的文本
if current_text:
result.append({'type': 'text', 'content': ''.join(current_text)})
# 处理表格
elif element.tag.endswith('tbl'):
table = docx.table.Table(element, doc)
for row in table.rows:
for cell in row.cells:
for paragraph in cell.paragraphs:
current_text = []
for run in paragraph.runs:
# 收集文本
if run.text.strip():
current_text.append(run.text)
# 提取图片
images, img_counter = extract_images_from_run(run, img_dir, img_counter)
for img_path in images:
if current_text:
result.append({'type': 'text', 'content': ''.join(current_text)})
current_text = []
result.append({'type': 'image', 'path': img_path})
# 处理剩余的文本
if current_text:
result.append({'type': 'text', 'content': ''.join(current_text)})
return result
# 使用示例
if __name__ == "__main__":
docx_path = "D:\\AI Hub 1.6.2 版本.docx"
output = parse_docx(docx_path)
# 打印输出结果
for item in output:
if item['type'] == 'text':
print(f"文本内容:{item['content']}")
else:
print(f"图片路径:{item['path']}")
结果
文本内容:文本内容1
文本内容:文本内容2
文本内容:文本内容3
图片路径:output_images\image1.png
图片路径:output_images\image2.png
图片路径:output_images\image3.png
文本内容:文本内容4
文本内容:文本内容5
文本内容:文本内容6
图片路径:output_images\image4.png
文本内容:添加
图片路径:output_images\image7.png
文本内容:查看
图片路径:output_images\image8.png
通过这个方式,可以快速进行文档解析,将解析的内容同步到LLM 让LLM 进行解析
标签:word,img,python,text,image,run,文档,images,path From: https://blog.csdn.net/serviceLive/article/details/146025284