温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

使用Python怎么将pdf文档转换成txt文档

发布时间:2021-02-23 15:48:42 来源:亿速云 阅读:237 作者:戴恩恩 栏目:开发技术

这篇文章主要为大家详细介绍了使用Python怎么将pdf文档转换成txt文档,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:

python可以做什么

Python是一种编程语言,内置了许多有效的工具,Python几乎无所不能,该语言通俗易懂、容易入门、功能强大,在许多领域中都有广泛的应用,例如最热门的大数据分析,人工智能,Web开发等。

import os.path
from pdfminer.pdfparser import PDFParser,PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal,LAParams
from pdfminer.pdfinterp import PDFTextExtractionNotAllowed
class CPdf2TxtManager():
  '''''
  classdocs
  '''
  def __init__(self):
    '''''
    Constructor
    '''
  def changePdfToText(self, filePath):
    file = open(path, 'rb') # 以二进制读模式打开
    #用文件对象来创建一个pdf文档分析器
    praser = PDFParser(file)
    # 创建一个PDF文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    praser.set_document(doc)
    doc.set_parser(praser)
    # 提供初始化密码
    # 如果没有密码 就创建一个空的字符串
    doc.initialize()
    # 检测文档是否提供txt转换,不提供就忽略
    if not doc.is_extractable:
      raise PDFTextExtractionNotAllowed
    # 创建PDf 资源管理器 来管理共享资源
    rsrcmgr = PDFResourceManager()
    # 创建一个PDF设备对象
    laparams = LAParams()
    device = PDFPageAggregator(rsrcmgr, laparams=laparams)
    # 创建一个PDF解释器对象
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    pdfStr = ''
    # 循环遍历列表,每次处理一个page的内容
    for page in doc.get_pages(): # doc.get_pages() 获取page列表
      interpreter.process_page(page)
      # 接受该页面的LTPage对象
      layout = device.get_result()
      # 这里layout是一个LTPage对象 里面存放着 这个page解析出的各种对象 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 想要获取文本就获得对象的text属性,
      for x in layout:
        if (isinstance(x, LTTextBoxHorizontal)):
          pdfStr = pdfStr + x.get_text() + '\n'
    fileNames = os.path.splitext(filePath)
    file2 = open(fileNames[0] + '.txt','wb')#保存这些内容
    file2.write(pdfStr.encode())
    file2.close()
    file.close()
if __name__ == '__main__':
  '''''
   解析pdf 文本,保存到txt文件中
  '''
  path = r'C:\Users\Administrator\Desktop\《精力管理》.pdf'
  pdf2TxtManager = CPdf2TxtManager()
  pdf2TxtManager.changePdfToText(path)

以上就是亿速云小编为大家收集整理的使用Python怎么将pdf文档转换成txt文档,如何觉得亿速云网站的内容还不错,欢迎将亿速云网站推荐给身边好友。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI