pdfminer3k應用
python處理pdf也是常用的技術了,pdfminer3k是一個非常好的工具。
先在系統目錄下建立pip目錄,呈現 C:\Users\Administrator\pip,之後建立pip.ini文本文件,內容如下:
[global]
index-url=http://mirrors.aliyun.com/pypi/simple/
[install]
trusted-host=mirrors.aliyun.com
#安裝最好通過設置國內代理下載安裝,如阿里、北清等 ,以上我是通過阿里雲代理,每次安裝都很順利,在此感謝阿里!
安裝 pip install pdfminer3k
首先,通用腳本讀取pdf中的文本:
from io import StringIO
from io import open
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
def read_pdf(pdf):
# resource manager
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
# device
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
process_pdf(rsrcmgr, device, pdf)
device.close()
content = retstr.getvalue()
retstr.close()
# 獲取所有行
lines = str(content).split("\n")
return lines
if __name__ == '__main__':
with open('t1.pdf', "rb") as my_pdf:
print(read_pdf(my_pdf))
我主要是想在pdf中抽出自己想要的一些關鍵信息,所以需要找到這些信息的共同點。幸運的是,這些關鍵信息的行都含有'//',所以我只需找到含有'//'的行就行了,於是寫了以下腳本。
這樣就可以直接使用了,我們先看腳本:
from io import StringIO
from io import open
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfinterp import PDFResourceManager, process_pdf
def read_pdf(pdf):
# resource manager
rsrcmgr = PDFResourceManager()
retstr = StringIO()
laparams = LAParams()
# device
device = TextConverter(rsrcmgr, retstr, laparams=laparams)
process_pdf(rsrcmgr, device, pdf)
device.close()
content = retstr.getvalue()
retstr.close()
# 獲取所有行
lines = str(content).split("\n")
units = [1, 2, 3, 5, 7, 8, 9, 11, 12, 13]
header = '\x0cUNIT '
# print(lines[0:100])
count = 0
flag = False
text = open('words.txt', 'w+')
for line in lines:
if line.startswith(header):
flag = False
count += 1
if count in units:
flag = True
print(line)
text.writelines(line + '\n')
if '//' in line and flag:
text_line = line.split('//')[0].split('. ')[-1]
print(text_line)
text.writelines(text_line+'\n')
text.close()
def _main():
my_pdf = open('t1.pdf', "rb")
read_pdf(my_pdf)
my_pdf.close()
if __name__ == '__main__':
_main()
其實看到lines = str(content).split("\n")那一行就夠了,我們可以把lines都print出來,就可以看到pdf裏面的內容。
這樣我們就可以把pdf文件處理看作簡單的字符串數據處理了。