当前位置:   article > 正文

python批量抓取多个pdf文件中固定位置字段_python读取pdf指定位置文字

python读取pdf指定位置文字
  1. import os
  2. import codecs
  3. import PyPDF2
  4. import pdfplumber
  5. def extract_content(pdf_path):
  6. # 内容提取,使用 pdfplumber 打开 PDF,用于提取文本
  7. with pdfplumber.open(pdf_path) as pdf_file:
  8. # 使用 PyPDF2 打开 PDF 用于提取图片
  9. pdf_image_reader = PyPDF2.PdfReader(open(pdf_path, "rb"))
  10. #print(len(pdf_image_reader.pages) )
  11. content = ''
  12. # len(pdf.pages)为PDF文档页数,一页页解析
  13. for i in range(len(pdf_file.pages)):
  14. #print("当前第 %s 页" % i)
  15. # pdf.pages[i] 是读取PDF文档第i+1页
  16. page_text = pdf_file.pages[i]
  17. # page.extract_text()函数即读取文本内容
  18. page_content = page_text.extract_text()
  19. if page_content:
  20. content = content + page_content + "\n"
  21. with open('content.txt', mode='w', encoding='utf-8') as f:
  22. for i in content:
  23. f.write(i)
  24. f.close()
  25. # 将文件中的文本读取出来并存入content.txt中
  26. f = codecs.open('content.txt', mode='r', encoding='utf-8') # 打开txt文件,以‘utf-8'编码读取
  27. line = f.readline() # 以行的形式进行读取文件
  28. x = [] # 设置x数组
  29. while line:
  30. a = line.split('\r\n') # 每行数据分隔情况,此数据以“\r\n”分隔
  31. b = a[0] # 选取需要读取的数据列数
  32. x.append(b) # 将其添加在列表之中
  33. line = f.readline()
  34. f.close() # close文件
  35. #print(x[9])
  36. x1 = x[9] # 读取出x列表中第10个的内容
  37. x2 = x[11]
  38. with open('version.txt', mode='a', encoding='utf-8') as f: # 列表中第10个的内容可追加的写入version.txt中
  39. for i in x1:
  40. f.write(i)
  41. f.write("\n")
  42. f.close() # close文件
  43. with open('password.txt', mode='a', encoding='utf-8') as f:
  44. for i in x2:
  45. f.write(i)
  46. f.write("\n")
  47. f.close() # close文件
  48. def strip_suffix(filename):
  49. return filename[:filename.rfind('.')]
  50. # 遍历列表中的所有文件
  51. def pdf_files(file_dir):
  52. for file in file_dir:
  53. if not os.path.isdir(file_dir):
  54. print("usage: python3 csv.py csv_dirname out_putfile")
  55. return []
  56. list_csv = []
  57. dir_list = os.listdir(file_dir)
  58. for file in dir_list:
  59. path = os.path.join(file_dir, file)
  60. if os.path.splitext(path)[1] == '.pdf':
  61. list_csv.append(path)
  62. #print(list_csv)
  63. return list_csv
  64. if __name__ == '__main__':
  65. file_dir = r'C:\Users\m1317\Desktop\allfiles' #pdf文件位置
  66. pdf_files = pdf_files(file_dir)
  67. for pdf_file in pdf_files:
  68. extract_content(pdf_file)

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/51406
推荐阅读
相关标签
  

闽ICP备14008679号