Python---提取Word中的文本内容

Python—提取Word中的文本内容

pip install python-docx

将doc转为docx

# window环境
from win32com import client as wc

word = wc.Dispatch("Word.Application")
doc = word.Documents.Open(os.path.join(os.getcwd(), doc_path))
doc.SaveAs(os.path.join(os.getcwd(), docx_path), 12)   # 12为docx
doc.Close()
word.Quit()

# linux环境
import subprocess
output = subprocess.check_output(["soffice","--headless","--invisible","--convert-to","docx","/home/requiem/workspace/python3/test.doc","--outdir","/home/requiem/workspace/python3/"])

获取段落文本

from docx import Document

def get_paragraphs(docx_path):
    #打开word文档
    document = Document(docx_path)
    
    #获取所有段落
    all_paragraphs = document.paragraphs
    
    paragraph_texts = []
    # 循环读取列表
    for paragraph in all_paragraphs:
        paragraph_texts.append(paragraph.text)
    
    return paragraph_texts

docx_path = "xxxx.docx"
paragraph_texts = get_paragraphs(docx_path)
for item in paragraph_texts:
    print(item)

# 将文本中 '\n' 去除,然后写入txt文件中查看
with open(docx_path[:-4] + 'txt', 'w', encoding='utf-8') as file:
    for item in paragraph_texts:
        if not item:
            continue
        # print(item)
        file.write(item.replace("\n", "")+'\n')

获取较段落更细粒度的文本

#打开word文档
document = Document(docx_path)

#获取所有段落
all_paragraphs = document.paragraphs

for paragraph in all_paragraphs:
    # 打印每一个段落的文字
    # print(paragraph.text)
    # 循环读取每个段落里的run内容
    for run in paragraph.runs:
        print(run.text) #打印run内容

读取Word中表格内的内容

way1

from docx import Document

def get_table_text(docx_path):
    """
        获取Word文档中的表格内容
    """
    result = []
    document = Document(docx_path) #读入文件
    tables = document.tables #获取Word文件中的表格集
    for table in tables: # 遍历每个表格 
        table_content = []
        for row in table.rows: # 从表格第一行开始循环读取表格数据
            row_content = get_cell_content(row.cells)
            table_content.append(row_content)
        result.append(table_content)
                
    return result


def get_cell_content(cells):
    """
        获取每一行中每一列的内容
    """
    row_content = []
    for cell in cells: # 遍历每一行的每一个单元格
    	# cell数量为表格最大列数+1,故对于较少列的行存在重复值,需去重
        if cell.text and cell.text not in row_content:
            row_content.append(cell.text)
        
    return row_content
    
docx_path = "xxxx.docx"
get_table_text(docx_path)

way2

import zipfile #解压文件库

docx_path = "xxx.docx"
#先将要处理的word文档用zipfile进行压缩
word = zipfile.ZipFile(docx_path)

#找到要处理的xml文件并以utf-8的格式读取
xml = word.read('word/document.xml').decode('utf-8')

#打印看看
print(type(xml)) #字符串
# print(xml) #打印整个字符串

#接下来分割字符串并存储到列表中
xml_list = xml.split('<w:t>') #以字符串<w:t>进行分割字符串
print(type(xml_list)) #是列表
# print(xml_list) #列表内容

#开始切片,找标签</w:t>
text_list = [] #新建空list用以存储切出来的数据
#开始循环读取列表xml_list
for i in xml_list:
    #条件查找
    if i.find('</w:t>') + 1: #切片查找是如果没找到是会返回-1,我们+1让他返回0,再运行else分支
        text_list.append(i[:i.find('</w:t>')]) #如果不是返回0就把找到的依次追加到text_list末尾
print(text_list)

参考博客:Python读取word文档内容

    原文作者:Dusk2090
    原文地址: https://blog.csdn.net/qq_41982466/article/details/116941071
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞