写一段python代码实现下面功能:1、读取指定文件夹中所有的word文档。2、提取文档内所有段落的首句如果首句不在一行请合并为一句。3、将提取的内容保存在word所在文件夹中的Excel里面
以下是Python代码实现:
import os
import docx
import openpyxl
# 读取指定文件夹中所有的word文档
folder_path = "path/to/folder"
docx_files = [f for f in os.listdir(folder_path) if f.endswith(".docx")]
# 提取文档内所有段落的首句
first_sentences = []
for docx_file in docx_files:
doc = docx.Document(os.path.join(folder_path, docx_file))
for para in doc.paragraphs:
# 如果首句不在一行,请合并为一句
text = para.text.strip()
if text:
if "\n" in text:
text = text.split("\n")[0].strip()
first_sentences.append(text)
# 将提取的内容保存在word所在文件夹中的Excel里面
wb = openpyxl.Workbook()
ws = wb.active
for i, sentence in enumerate(first_sentences):
ws.cell(row=i+1, column=1, value=sentence)
wb.save(os.path.join(folder_path, "first_sentences.xlsx"))
需要注意的是,需要安装docx和openpyxl这两个库。可以通过以下命令安装:
pip install python-docx openpyxl
原文地址: https://www.cveoy.top/t/topic/bnvL 著作权归作者所有。请勿转载和采集!