Python 代码:从 Word 文档提取首句并保存到 Excel
以下是 Python 代码实现:
import os
import docx
import openpyxl
# 读取指定文件夹中所有的word文档
folder_path = 'path/to/folder'
ddocx_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/mP55 著作权归作者所有。请勿转载和采集!