赞
踩
在日常工作和学习中,我们经常需要从PDF、Word文档中提取文本,例如为了数据分析和文本处理等。如果手动进行这些操作,不仅费时费力,而且容易出错。因此,编写一个文本内容提取变得尤为重要。本文将介绍如何使用Python编写一个文本内容提取,该工具可以从PDF、Word文档中提取文本。
文本内容提取的核心原理是遍历指定目录下的所有文件,根据文件类型(PDF或Word)使用相应的库提取文本,然后将提取的文本保存到指定目录。在这个过程中,我们需要考虑以下几个问题:
在设计文本内容提取时,我们需要考虑以下几个方面的内容:
接下来,我们将详细介绍文本内容提取的实现过程。为了方便起见,我们将使用Python编写这个工具。
import os
def traverse_dir(dir_path):
file_list = []
for root, dirs, files in os.walk(dir_path):
for file in files:
file_list.append(os.path.join(root, file))
return file_list
import PyPDF2
def extract_text_from_pdf(pdf_path, output_path):
with open(pdf_path, 'rb') as file:
pdf_reader = PyPDF2.PdfFileReader(file)
for page_num in range(pdf_reader.numPages):
page = pdf_reader.getPage(page_num)
text = page.extractText()
with open(output_path, 'a', encoding='utf-8') as output_file:
output_file.write(text)
对于Word文档,我们可以使用Python的python-docx库来提取文本。具体实现如下:
from docx import Document
def extract_text_from_docx(docx_path, output_path):
doc = Document(docx_path)
text = []
for para in doc.paragraphs:
text.append(para.text)
with open(output_path, 'a', encoding='utf-8') as output_file:
output_file.write('\n'.join(text))
import os
def save_text(text, output_path):
with open(output_path, 'w', encoding='utf-8') as output_file:
output_file.write(text)
import argparse import os import PyPDF2 from docx import Document def traverse_dir(dir_path): file_list = [] for root, dirs, files in os.walk(dir_path): for file in files: file_list.append(os.path.join(root, file)) return file_list def extract_text_from_pdf(pdf_path, output_path): with open(pdf_path, 'rb') as file: pdf_reader = PyPDF2.PdfFileReader(file) for page_num in range(pdf_reader.numPages): page = pdf_reader.getPage(page_num) text = page.extractText() with open(output_path, 'a', encoding='utf-8') as output_file: output_file.write(text) def extract_text_from_docx(docx_path, output_path): doc = Document(docx_path) text = [] for para in doc.paragraphs: text.append(para.text) with open(output_path, 'a', encoding='utf-8') as output_file: output_file.write('\n'.join(text)) def save_text(text, output_path): with open(output_path, 'w', encoding='utf-8') as output_file: output_file.write(text) def main(): parser = argparse.ArgumentParser(description="文本内容提取") parser.add_argument("directory", help="指定目录") parser.add_argument("output_directory", help="指定输出目录") args = parser.parse_args() dir_path = args.directory output_dir = args.output_directory file_list = traverse_dir(dir_path) for file_path in file_list: if file_path.lower().endswith(('.pdf')): extract_text_from_pdf(file_path, output_dir) elif file_path.lower().endswith(('.docx', '.doc')): extract_text_from_docx(file_path, output_dir) if __name__ == "__main__": main()
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。