欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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循環(huán)進行批量操作

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文檔內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 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實時監(jiān)控cpu小工具

    python實時監(jiān)控cpu小工具

    這篇文章主要為大家詳細介紹了python實時監(jiān)控cpu的小工具,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-06-06
  • Blender?Python編程實現批量導入網格并保存渲染圖像

    Blender?Python編程實現批量導入網格并保存渲染圖像

    這篇文章主要為大家介紹了Blender?Python?編程實現批量導入網格并保存渲染圖像示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • PyTorch搭建CNN實現風速預測

    PyTorch搭建CNN實現風速預測

    PyTorch是一個開源的Python機器學習庫,基于Torch,用于自然語言處理等應用程序。它不僅能夠實現強大的GPU加速,同時還支持動態(tài)神經網絡。本文將介紹PyTorch搭建CNN如何實現風速預測,感興趣的可以學習一下
    2021-12-12

最新評論