概述
file_path = r’替换pdf文件路径’ #需要遍历的文件夹路径
pdf = pdfplumber.open(file_path) #打开pdf文件
pages = pdf.pages #获取pdf文件列表
text_all = []
for page in pages:
text = page.extract_text() #提取当前页面文本
text_all.append(text) #增加当前页面文本到列表中
text_all = ‘’.join(text_all) #把列表转成字符串
pdf.close()
<a name="GVpmh"></a>
## 2.保存文本
```python
with open("文本提取.txt",'a',encoding = 'utf-8')as text_file:
text_file.write(text_all)
3.批量提取
使用walk()函数遍历文件夹
遍历指定文件夹下的所有子文件夹及子文件夹里的所有文件信息。
import os
#遍历所有pdf文件
file_dir = r'F:\Python\python 代码\pdf解析' #需要遍历的文件夹路径
file_list = []
for files in os.walk(file_dir): #遍历文件夹及其下的所有子文件夹
print(files)
for file in files[2]:
print(file)
if os .path.splitext(file)[1] =='.pdf' or os.path.splitext(file)[1] == '.PDF':
file_list.append(file_dir + '\\' +file)
print(file_list)
全代码
#pdf文本解析
import pdfplumber
import os
#遍历所有pdf文件
file_dir = r'C:\Users\luo\Desktop\pdf解析' #需要遍历的文件夹路径
file_list = []
for files in os.walk(file_dir): #遍历文件夹及其下的所有子文件夹
#print(files)
for file in files[2]:
#print(file)
if os .path.splitext(file)[1] =='.pdf' or os.path.splitext(file)[1] == '.PDF':
file_list.append(file_dir + '\\' +file)
print(file_list)
for file_path in file_list:
pdf = pdfplumber.open(file_path) #打开pdf文件
pages = pdf.pages #获取pdf文件列表
print(pages)
text_all = []
for page in pages:
text = page.extract_text() #提取当前页面文本
text_all.append(text) #增加当前页面文本到列表中
text_all = ''.join(text_all) #把列表转成字符串
pdf.close()
print(text_all)
#保存文本内容为txt
with open("文本提取.txt",'a',encoding = 'utf-8')as text_file:
text_file.write(text_all)