python處理pdf也是常用的技術(shù)了,對(duì)于python3來說,pdfminer3k是一個(gè)非常好的工具。
首先,為了滿足大部分人的需求,我先給一個(gè)通用一點(diǎn)的腳本來讀取pdf中的文本:
from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfinterp import PDFResourceManager, process_pdf rsrcmgr = PDFResourceManager() device = TextConverter(rsrcmgr, retstr, laparams=laparams) process_pdf(rsrcmgr, device, pdf) content = retstr.getvalue() lines = str(content).split('\n') if __name__ == '__main__': with open('t1.pdf', 'rb') as my_pdf:
我主要是想在pdf中抽出自己想要的一些關(guān)鍵信息,所以需要找到這些信息的共同點(diǎn)。幸運(yùn)的是,這些關(guān)鍵信息的行都含有'//',所以我只需找到含有'//'的行就行了,于是寫了以下腳本。
這樣就可以直接使用了,我們先看腳本:
from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfinterp import PDFResourceManager, process_pdf rsrcmgr = PDFResourceManager() device = TextConverter(rsrcmgr, retstr, laparams=laparams) process_pdf(rsrcmgr, device, pdf) content = retstr.getvalue() lines = str(content).split('\n') units = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13] text = open('words.txt', 'w+') if line.startswith(header): text.writelines(line + '\n') if '//' in line and flag: text_line = line.split('//')[0].split('. ')[-1] text.writelines(text_line+'\n') my_pdf = open('t1.pdf', 'rb') if __name__ == '__main__':
其實(shí)看到lines = str(content).split('\n')那一行就夠了,我們可以把lines都print出來,就可以看到pdf里面的內(nèi)容。
這樣我們就可以把pdf文件處理看作簡(jiǎn)單的字符串?dāng)?shù)據(jù)處理了。接下來的腳本操作也不用過多解釋了。
|