python pdf转txt保留全部信息_Python 将pdf转换成txt(不处理图片)
上一篇文章中已經(jīng)介紹了簡(jiǎn)單的python爬網(wǎng)頁(yè)下載文檔,但下載后的文檔多為doc或pdf,對(duì)于數(shù)據(jù)處理仍然有很多限制,所以將doc/pdf轉(zhuǎn)換成txt顯得尤為重要。查找了很多資料,在linux下要將doc轉(zhuǎn)換成txt確實(shí)有難度,所以考慮先將pdf轉(zhuǎn)換成txt。
師兄推薦使用PDFMiner來(lái)處理,嘗試了一番,確實(shí)效果不錯(cuò),在此和大家分享。
PDFMiner?的簡(jiǎn)介:PDFMiner is a tool for extracting information from PDF documents. Unlike other PDF-related tools, it focuses entirely on getting and analyzing text data.有興趣的同學(xué)請(qǐng)通過(guò)官網(wǎng)進(jìn)行詳細(xì)查看,通過(guò)PDFMiner中的小工具pdf2txt.py,便能將pdf轉(zhuǎn)換成txt,而且仍保留pdf中的格式,超贊!
閱讀pdf2txt.py的源碼,我們可以看到具體的實(shí)現(xiàn)步驟,為了以后能處理大規(guī)模的pdf文件,這里我們只提取出pdf轉(zhuǎn)換成txt的部分,具體實(shí)現(xiàn)代碼如下:
# -*- coding: utf-8 -*-
#-----------------------------------------------------
# 功能:將pdf轉(zhuǎn)換成txt(不處理圖片)
# 作者:chenbjin
# 日期:2014-07-11
# 語(yǔ)言:Python 2.7.6
# 環(huán)境:linux(ubuntu)
# PDFMiner20140328(Must be installed)
# 使用:python pdf2txt.py file.pdf
#-----------------------------------------------------
import sys
from pdfminer.pdfinterp import PDFResourceManager,PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
#main
def main(argv) :
#輸出文件名,這里只處理單文檔,所以只用了argv[1]
outfile = argv[1] + ‘.txt‘
args = [argv[1]]
debug = 0
pagenos = set()
password = ‘‘
maxpages = 0
rotation = 0
codec = ‘utf-8‘ #輸出編碼
caching = True
imagewriter = None
laparams = LAParams()
#
PDFResourceManager.debug = debug
PDFPageInterpreter.debug = debug
rsrcmgr = PDFResourceManager(caching=caching)
outfp = file(outfile,‘w‘)
#pdf轉(zhuǎn)換
device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams,
imagewriter=imagewriter)
for fname in args:
fp = file(fname,‘rb‘)
interpreter = PDFPageInterpreter(rsrcmgr, device)
#處理文檔對(duì)象中每一頁(yè)的內(nèi)容
for page in PDFPage.get_pages(fp, pagenos,
maxpages=maxpages, password=password,
caching=caching, check_extractable=True) :
page.rotate = (page.rotate+rotation) % 360
interpreter.process_page(page)
fp.close()
device.close()
outfp.close()
return
if __name__ == ‘__main__‘ : main(sys.argv)
下一步將嘗試將pdf中的圖片進(jìn)行轉(zhuǎn)換,可以通過(guò)http://denis.papathanasiou.org/2010/08/04/extracting-text-images-from-pdf-files/ 進(jìn)行了解。
參考資料:
1.PDFMiner:http://www.unixuser.org/~euske/python/pdfminer/
總結(jié)
以上是生活随笔為你收集整理的python pdf转txt保留全部信息_Python 将pdf转换成txt(不处理图片)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: fastjson反序列化过滤字段属性_原
- 下一篇: rocketmq 消息指定_进大厂必备的