python批量处理PDF文档输出自定义关键词的出现次数

 更新时间:2023年04月11日 11:54:12   作者:Ryo_Yuki  
这篇文章主要介绍了python批量处理PDF文档,输出自定义关键词的出现次数,文中有详细的代码示例,需要的朋友可以参考阅读

函数模块介绍

具体的代码可见全部代码部分,这部分只介绍思路和相应的函数模块

对文件进行批量重命名

因为文件名是中文,且无关于最后的结果,所以批量命名为数字
注意如果不是第一次运行,即已经命名完成,就在主函数内把这个函数注释掉就好了

def rename():
    path='dealPdf'
    filelist=os.listdir(path)
    for i,files in enumerate(filelist):
        Olddir=os.path.join(path,files)
        if os.path.isdir(Olddir):
            continue
        Newdir=os.path.join(path,str(i+1)+'.pdf')
        os.rename(Olddir,Newdir)

将PDF转化为txt

PDF是无法直接进行文本分析的,所以需要将文字转成txt文件(PDF中图内的文字无法提取)

#将pdf文件转化成txt文件
def pdf_to_txt(dealPdf,index):
    # 不显示warning
    logging.propagate = False
    logging.getLogger().setLevel(logging.ERROR)
    pdf_filename = dealPdf
    device = PDFPageAggregator(PDFResourceManager(), laparams=LAParams())
    interpreter = PDFPageInterpreter(PDFResourceManager(), device)    
    parser = PDFParser(open(pdf_filename, 'rb'))
    doc = PDFDocument(parser)
    
    
    txt_filename='dealTxt\\'+str(index)+'.txt'
        
    # 检测文档是否提供txt转换,不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        with open(txt_filename, 'w', encoding="utf-8") as fw:
            #print("num page:{}".format(len(list(doc.get_pages()))))
            for i,page in enumerate(PDFPage.create_pages(doc)):
                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):
                        results = x.get_text()
                        fw.write(results)

删除txt中的换行符

因为PDF导出的txt会用换行符换行,为了避免词语因此拆开,所以删除所有的换行符

#对txt文件的换行符进行删除
def delete_huanhangfu(dealTxt,index):
    outPutString=''
    outPutTxt='outPutTxt\\'+str(index)+'.txt'
    with open(dealTxt,'r',encoding="utf-8") as f:
        lines=f.readlines()
        for i in range(len(lines)):
            if lines[i].endswith('\n'):
                lines[i]=lines[i][:-1] #将字符串末尾的\n去掉
        for j in range(len(lines)):
            outPutString+=lines[j]
    with open(outPutTxt,'w',encoding="utf-8") as fw:
        fw.write(outPutString)

添加自定义词语

此处可以根据自己的需要自定义,传入的wordsByMyself是全局变量

分词与词频统计

调用jieba进行分词,读取通用词表去掉停用词(此步其实可以省略,对最终结果影响不大),将词语和出现次数合成为键值对,输出关键词出现次数

#分词并进行词频统计
def cut_and_count(outPutTxt):
    with open(outPutTxt,encoding='utf-8') as f: 
        #step1:读取文档并调用jieba分词
        text=f.read() 
        words=jieba.lcut(text)
        #step2:读取停用词表,去停用词
        stopwords = {}.fromkeys([ line.rstrip() for line in open('stopwords.txt',encoding='utf-8') ])
        finalwords = []
        for word in words:
            if word not in stopwords:
                if (word != "。" and word != ",") :
                    finalwords.append(word)       
        
        
        #step3:统计特定关键词的出现次数
        valuelist=[0]*len(wordsByMyself)
        counts=dict(zip(wordsByMyself,valuelist))
        for word in finalwords:
            if len(word) == 1:#单个词不计算在内
                continue
            else:
                counts[word]=counts.get(word,0)+1#遍历所有词语,每出现一次其对应值加1
        for i in range(len(wordsByMyself)):
            if wordsByMyself[i] in counts:
                print(wordsByMyself[i]+':'+str(counts[wordsByMyself[i]]))
            else:
                print(wordsByMyself[i]+':0')

主函数

通过for循环进行批量操作

if __name__ == "__main__":
    #rename()   
    for i in range(1,fileNum+1):
        pdf_to_txt('dealPdf\\'+str(i)+'.pdf',i)#将pdf文件转化成txt文件,传入文件路径 
        delete_huanhangfu('dealTxt\\'+str(i)+'.txt',i)#对txt文件的换行符进行删除,防止词语因换行被拆分
        word_by_myself()#添加自定义词语
        print(f'----------result {i}----------')
        cut_and_count('outPutTxt\\'+str(i)+'.txt')#分词并进行词频统计,传入文件路径

本地文件结构

全部代码

import jieba
import jieba.analyse
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LTTextBoxHorizontal, LAParams
from pdfminer.pdfpage import PDFPage,PDFTextExtractionNotAllowed
import logging
import os

wordsByMyself=['社会责任','义务','上市','公司'] #自定义词语,全局变量
fileNum=16#存储总共待处理的文件数量

#重命名所有文件夹下的文件,适应处理需要
def rename():
    path='dealPdf'
    filelist=os.listdir(path)
    for i,files in enumerate(filelist):
        Olddir=os.path.join(path,files)
        if os.path.isdir(Olddir):
            continue
        Newdir=os.path.join(path,str(i+1)+'.pdf')
        os.rename(Olddir,Newdir)

#将pdf文件转化成txt文件
def pdf_to_txt(dealPdf,index):
    # 不显示warning
    logging.propagate = False
    logging.getLogger().setLevel(logging.ERROR)
    pdf_filename = dealPdf
    device = PDFPageAggregator(PDFResourceManager(), laparams=LAParams())
    interpreter = PDFPageInterpreter(PDFResourceManager(), device)    
    parser = PDFParser(open(pdf_filename, 'rb'))
    doc = PDFDocument(parser)
    
    
    txt_filename='dealTxt\\'+str(index)+'.txt'
        
    # 检测文档是否提供txt转换,不提供就忽略
    if not doc.is_extractable:
        raise PDFTextExtractionNotAllowed
    else:
        with open(txt_filename, 'w', encoding="utf-8") as fw:
            #print("num page:{}".format(len(list(doc.get_pages()))))
            for i,page in enumerate(PDFPage.create_pages(doc)):
                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):
                        results = x.get_text()
                        fw.write(results)

#对txt文件的换行符进行删除
def delete_huanhangfu(dealTxt,index):
    outPutString=''
    outPutTxt='outPutTxt\\'+str(index)+'.txt'
    with open(dealTxt,'r',encoding="utf-8") as f:
        lines=f.readlines()
        for i in range(len(lines)):
            if lines[i].endswith('\n'):
                lines[i]=lines[i][:-1] #将字符串末尾的\n去掉
        for j in range(len(lines)):
            outPutString+=lines[j]
    with open(outPutTxt,'w',encoding="utf-8") as fw:
        fw.write(outPutString)
            
#添加自定义词语    
def word_by_myself():
    for i in range(len(wordsByMyself)):
        jieba.add_word(wordsByMyself[i])

#分词并进行词频统计
def cut_and_count(outPutTxt):
    with open(outPutTxt,encoding='utf-8') as f: 
        #step1:读取文档并调用jieba分词
        text=f.read() 
        words=jieba.lcut(text)
        #step2:读取停用词表,去停用词
        stopwords = {}.fromkeys([ line.rstrip() for line in open('stopwords.txt',encoding='utf-8') ])
        finalwords = []
        for word in words:
            if word not in stopwords:
                if (word != "。" and word != ",") :
                    finalwords.append(word)       
        
        
        #step3:统计特定关键词的出现次数
        valuelist=[0]*len(wordsByMyself)
        counts=dict(zip(wordsByMyself,valuelist))
        for word in finalwords:
            if len(word) == 1:#单个词不计算在内
                continue
            else:
                counts[word]=counts.get(word,0)+1#遍历所有词语,每出现一次其对应值加1
        for i in range(len(wordsByMyself)):
            if wordsByMyself[i] in counts:
                print(wordsByMyself[i]+':'+str(counts[wordsByMyself[i]]))
            else:
                print(wordsByMyself[i]+':0')

#主函数 
if __name__ == "__main__":
    rename()   
    for i in range(1,fileNum+1):
        pdf_to_txt('dealPdf\\'+str(i)+'.pdf',i)#将pdf文件转化成txt文件,传入文件路径 
        delete_huanhangfu('dealTxt\\'+str(i)+'.txt',i)#对txt文件的换行符进行删除,防止词语因换行被拆分
        word_by_myself()#添加自定义词语
        print(f'----------result {i}----------')
        cut_and_count('outPutTxt\\'+str(i)+'.txt')#分词并进行词频统计,传入文件路径

结果预览

到此这篇关于python批量处理PDF文档输出自定义关键词的出现次数的文章就介绍到这了,更多相关python处理PDF文档内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • python和websocket构建实时日志跟踪器的步骤

    python和websocket构建实时日志跟踪器的步骤

    这篇文章主要介绍了python和websocket构建实时日志跟踪器的步骤,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下
    2021-04-04
  • Python 蚁群算法详解

    Python 蚁群算法详解

    这篇文章主要介绍了Python编程实现蚁群算法详解,涉及蚂蚁算法的简介,主要原理及公式,以及Python中的实现代码,具有一定参考价值,需要的朋友可以了解下
    2021-10-10
  • 解决Keras 中加入lambda层无法正常载入模型问题

    解决Keras 中加入lambda层无法正常载入模型问题

    这篇文章主要介绍了解决Keras 中加入lambda层无法正常载入模型问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2020-06-06
  • Python使用PyMySql增删改查Mysql数据库的实现

    Python使用PyMySql增删改查Mysql数据库的实现

    PyMysql是Python中用于连接MySQL数据库的一个第三方库,本文主要介绍了Python使用PyMySql增删改查Mysql数据库的实现,具有一定的参考价值,感兴趣的可以了解一下
    2024-01-01
  • Python获取Redis所有Key以及内容的方法

    Python获取Redis所有Key以及内容的方法

    今天小编就为大家分享一篇Python获取Redis所有Key以及内容的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2019-02-02
  • python基础:面向对象详解

    python基础:面向对象详解

    这篇文章主要介绍了Python面向对象的相关内容,如果您想对Python编程的基础部分有所了解,这篇文章是值得一看的,需要的朋友可以参考下。
    2021-10-10
  • Python利用pynput实现划词复制功能

    Python利用pynput实现划词复制功能

    这篇文章主要为大家想详细介绍了Python如何利用pynput实现划词复制功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2022-05-05
  • python实时监控cpu小工具

    python实时监控cpu小工具

    这篇文章主要为大家详细介绍了python实时监控cpu的小工具,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-06-06
  • Blender Python编程实现批量导入网格并保存渲染图像

    Blender Python编程实现批量导入网格并保存渲染图像

    这篇文章主要为大家介绍了Blender Python 编程实现批量导入网格并保存渲染图像示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-08-08
  • PyTorch搭建CNN实现风速预测

    PyTorch搭建CNN实现风速预测

    PyTorch是一个开源的Python机器学习库,基于Torch,用于自然语言处理等应用程序。它不仅能够实现强大的GPU加速,同时还支持动态神经网络。本文将介绍PyTorch搭建CNN如何实现风速预测,感兴趣的可以学习一下
    2021-12-12

最新评论