因为工作需要 需要将一个word文档的内容分割成按标题的一个个字符串,本方法借用了网上一些方法加上自己的方法合成,因为试了网上大部分方法对于我的这个2文档都不行
教程:1.首先安装docx库 本地使用命令“pip install python-docx 虚拟环境开发通过
conda install python-docx
2.方法如下:原理:首先通过对word文档内容格式的xml来判断是否是标题(word中的格式) 包括(1,2,3级...)标题,如果是标题返回标题的级数,不是则返回none,后面通过循环(按节)来将内容拼接一起,最终将按标题分割内容存放在一个list中
from docx import Document
import re
def parse_word_document(doc_path):
doc = Document(doc_path)
titles = []
text=''
for paragraph in doc.paragraphs:
title = isTitle(paragraph)
#不是标题
if title is None:
text+=paragraph.text
text+='\n'
#是标题
else:
titles.append(text)
text = ''
text+=paragraph.text
text+='\n'
titles.append(text)
return titles
def getOutlineLevel(inputXml):
"""
功能 从xml字段中提取出<w:outlineLvl w:val="number"/>中的数字number
参数 inputXml
返回 number
"""
start_index = inputXml.find('<w:outlineLvl')
end_index = inputXml.find('>', start_index)
number = inputXml[start_index:end_index + 1]
number = re.search("\d+", number).group()
return number
def isTitle(paragraph):
"""
功能 判断该段落是否设置了大纲等级
参数 paragraph:段落
返回 None:普通正文,没有大纲级别 0:一级标题 1:二级标题 2:三级标题
"""
# 如果是空行,直接返回None
if paragraph.text.strip() == '':
return None
# 如果该段落是直接在段落里设置大纲级别的,根据xml判断大纲级别
paragraphXml = paragraph._p.xml
if paragraphXml.find('<w:outlineLvl') >= 0:
return getOutlineLevel(paragraphXml)
# 如果该段落是通过样式设置大纲级别的,逐级检索样式及其父样式,判断大纲级别
targetStyle = paragraph.style
while targetStyle is not None:
# 如果在该级style中找到了大纲级别,返回
if targetStyle.element.xml.find('<w:outlineLvl') >= 0:
return getOutlineLevel(targetStyle.element.xml)
else:
targetStyle = targetStyle.base_style
# 如果在段落、样式里都没有找到大纲级别,返回None
return None
doc_path = '某某word文档.docx'
titles = parse_word_document(doc_path)
for title in titles:
print(title)