获取pdf文件列表
#遍历文件夹中的每一个pdf
import os
file_dir=r"文件夹路径"
file_list=[]
for files in os.walk(file_dir):
for file in files[2]:
if os.path.splitext(file)[1]=='.pdf' or os.path.splitext(file)[1]=='.PDF':
file_list.append(file_dir+ '/' + file)
os.walk()返回一个生成器,每次迭代会返回一个元组,包含当前目录的路径、当前目录下的子目录列表和当前目录下的文件列表。在这个元组中,files[2]代表当前目录下的所有文件列表。
因此,在for循环中,for file in files[2]表示遍历当前目录下的所有文件。文件列表files[2]中存储了当前目录下的所有文件名,通过这个for循环可以逐个处理当前目录下的每个文件。
生成txt文件
#将pdf生成txt文件
import os
import pdfplumber
file_dir = "文件夹路径"
output_dir = "output路径" # 存放txt文件的目录
if not os.path.exists(output_dir):
os.makedirs(output_dir)
for file in file_list:
pdf_path = os.path.join(file_dir, file)
with pdfplumber.open(pdf_path) as pdf:
text_all = []
for page in pdf.pages:
text = page.extract_text()
text_all.append(text)
text_a = ''.join(text_all)
# 生成同名的txt文件
txt_filename = os.path.splitext(os.path.basename(file))[0] + '.txt'
txt_path = os.path.join(output_dir, txt_filename)
with open(txt_path, 'w', encoding='utf-8') as f:
f.write(text_a)
通过遍历file_list中的文件路径,使用pdfplumber打开每个PDF文件,并提取其中的文本信息。然后,将提取的文本信息写入一个同名的TXT文件中,并保存到指定的目录output_dir下。