专题04-python操作PDF文件

笔者是一个痴迷于挖掘数据中的价值的学习人,希望在平日的工作学习中,挖掘数据的价值,找寻数据的秘密,笔者认为,数据的价值不仅仅只体现在企业中,个人也可以体会到数据的魅力,用技术力量探索行为密码,让大数据助跑每一个人,欢迎直筒们关注我的公众号,大家一起讨论数据中的那些有趣的事情。

我的公众号为:livandata

在平时阅读时经常会用到pdf文档,很多书籍是pdf的格式,很多内容信息也以pdf的方式来传递,所以在使用python提高效率时便考虑了读取pdf的文档,以方便接下来的操作。

1、读取pdf文档中的内容:

下面的这段代码会将pdf的文件转换为txt的文档,转换完成后可以做其他的操作,近日应好友邀约做了一个关键字词频的分析,贴上来权当整理,后续有需要再进行优化:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import importlib
importlib.reload(sys)
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
import jieba
'''解析pdf 文本,保存到txt文件中'''
def parse(path):
    # 以二进制读模式打开
    fp = open(path, 'rb')
    #用文件对象来创建一个pdf文档分析器
    praser = PDFParser(fp)
    # 创建一个PDF文档
    doc = PDFDocument()
    # 连接分析器 与文档对象
    praser.set_document(doc)
    doc.set_parser(praser)
    # 提供初始化密码
    # 如果没有密码 就创建一个空的字符串
    doc.initialize()
    # 检测文档是否提供txt转换,不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        # 创建PDf 资源管理器 来管理共享资源
        rsrcmgr = PDFResourceManager()
        # 创建一个PDF设备对象
        laparams = LAParams()
        device = PDFPageAggregator(rsrcmgr, laparams=laparams)
        # 创建一个PDF解释器对象
        interpreter = PDFPageInterpreter(rsrcmgr, device)
        # 循环遍历列表,每次处理一个page的内容
        # doc.get_pages() 获取page列表
        results=''
        for page in doc.get_pages():
            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)):
                    result = x.get_text()
                    results = results+result
        return results
# 实现关键字的提取:
def extract(page, exclude):
    # 使用jieba进行分词,将文本分成词语列表
    words = jieba.lcut(page)
    print(words)
    count = {}
    # 使用 for 循环遍历每个词语并统计个数
    for word in words:
        # 排除单个字的干扰,使得输出结果为词语
        if len(word) < 2:
            continue
        else:
            # 如果字典里键为word的值存在,则返回键的值并加一,
            # 如果不存在键word,则返回0再加上1
            count[word] = count.get(word, 0) + 1
    # 遍历字典的所有键,即所有word
    key_list = []
    for key in count.keys():
        key_list.append(key)
    for key in key_list:
        if key in exclude:
            # 删除字典中键为无关词语的键值对
            del count[key]
    # 将字典的所有键值对转化为列表
    items_list = []
    for item in count.items():
        items_list.append(item)
    # 对列表按照词频从大到小的顺序排序
    items_list.sort(key=lambda x: x[1], reverse=True)
    # 此处统计排名前五的单词,所以range(5)
    list_result = []
    for i in range(5):
        word, number = items_list[i]
        result = "关键词:"+word+":"+str(number)
        list_result.append(result)
    return list_result

if __name__ == '__main__':
    # 把你需要分析的文件路径放在下面的list中:
    paths = ['/Users/*******/**/data/十九大报告.pdf',]
    for path in paths:
        page_result = parse(path)
        # 建立无关词语列表:即关键词中不需要呈现的词
        exclude = ["可以", "一起", "这样"]
        keyword = extract(page_result, exclude)
        print(keyword)

2、批量读取多个pdf文档:

pdf的批量读取是为了获取到多个pdf中的内容,借用刚才的包,可以循环调用上面读取的文件,形成循环读取。
#!/usr/bin/env python
# _*_ UTF-8 _*_
import os
import sys
import time
pdfs = (pdfs for pdfs in os.listdir('.') if pdfs.endswith('.pdf'))
for pdf1 in pdfs:
    pdf = pdf1.replace(' ', '_').replace('-', '_').replace('&', '_')
    os.rename(pdf1, pdf)
    print('=' * 30)
    print(pdf)
    txt = pdf[:-4] + '.txt'
    exe = '"' + sys.executable + '" "'
    pdf2txt = os.path.dirname(sys.executable)
    pdf2txt = pdf2txt + '\\scripts\\pdf2txt.py" -o '
    try:
        # 调用命令行工具pdf2txt.py进行转换
        # 如果pdf加密过可以改写下面的代码
        # 在-o前面使用-P来指定密码
        cmd = exe + pdf2txt + txt + ' ' + pdf
        os.popen(cmd)
        # 转换需要一定时间,一般小文件2秒钟足够了
        time.sleep(2)
        # 输出转换后的文本,前200个字符
        with open(txt, encoding='utf8') as fp:
            print(fp.read(200))
    except:
        pass

3、pdf文件的生成:

#!/usr/bin/python
# -*- coding: utf-8 -*-
from reportlab.pdfgen import canvas
from reportlab.platypus.tables import Table, TableStyle
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph,Frame
from reportlab.lib.pagesizes import letter, A4
from reportlab.platypus import Image as platImage
from PIL import Image
from reportlab.lib import colors
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase import pdfmetrics
#支持中文,需要下载相应的文泉驿中文字体
pdfmetrics.registerFont(TTFont('hei', 'hei.TTF'))
import testSubFun
testSubFun.testSubFunc('first')
#设置页面大小
c = canvas.Canvas('测试.pdf',pagesize=A4)
xlength,ylength = A4
print('width:%d high:%d'%(xlength,ylength))
#c.line(1,1,ylength/2,ylength)
#设置文字类型及字号
c.setFont('hei',20)
#生成一个table表格
atable = [[1,2,3,4],[5,6,7,8]]
t = Table(atable,50,20)
t.setStyle(TableStyle([('ALIGN',(0,0),(3,1),'CENTER'),
                       ('INNERGRID',(0,0),(-1,-1),0.25,colors.black),
                       ('BOX',(0,0),(-1,-1),0.25,colors.black)]))
textOb = c.beginText(1,ylength-10)
indexVlaue = 0
while(indexVlaue < ylength):
    textStr = '''test 中文写入测试中文写入测试中文写入测试中文写入测试%d'''%indexVlaue
    #print('nextline,nextline%d'%indexVlaue)
    textOb.textLine(textStr)
    indexVlaue = indexVlaue + 1
    break
c.drawText(textOb)
#简单的图片载入
imageValue = 'test.png'
c.drawImage(imageValue,97,97,300,300)
c.drawImage('test.png',50,50,50,50)
t.split(0,0)
t.drawOn(c,100,1)
c.showPage()
#换页的方式不同的showPage
c.drawString(0,0,'helloword')
c.showPage()
c.save()

以上为常用的pdf文件的读取和生成方式,复杂的部分可以后面逐渐的研究。

推荐文章为:

http://www.cnblogs.com/shengulong/p/7994082.html

发布了137 篇原创文章 · 获赞 93 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/livan1234/article/details/86707454