最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python批量處理PDF文檔輸出自定義關(guān)鍵詞的出現(xiàn)次數(shù)

 更新時(shí)間:2023年04月11日 11:54:12   作者:Ryo_Yuki  
這篇文章主要介紹了python批量處理PDF文檔,輸出自定義關(guān)鍵詞的出現(xiàn)次數(shù),文中有詳細(xì)的代碼示例,需要的朋友可以參考閱讀

函數(shù)模塊介紹

具體的代碼可見全部代碼部分,這部分只介紹思路和相應(yīng)的函數(shù)模塊

對文件進(jìn)行批量重命名

因?yàn)槲募侵形模覠o關(guān)于最后的結(jié)果,所以批量命名為數(shù)字
注意如果不是第一次運(yùn)行,即已經(jīng)命名完成,就在主函數(shù)內(nèi)把這個(gè)函數(shù)注釋掉就好了

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轉(zhuǎn)化為txt

PDF是無法直接進(jìn)行文本分析的,所以需要將文字轉(zhuǎn)成txt文件(PDF中圖內(nèi)的文字無法提取)

#將pdf文件轉(zhuǎn)化成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轉(zhuǎn)換,不提供就忽略
    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是一個(gè)LTPage對象 里面存放著 這個(gè)page解析出的各種對象
                # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等
                # 想要獲取文本就獲得對象的text屬性,
                for x in layout:
                    if isinstance(x, LTTextBoxHorizontal):
                        results = x.get_text()
                        fw.write(results)

刪除txt中的換行符

因?yàn)镻DF導(dǎo)出的txt會(huì)用換行符換行,為了避免詞語因此拆開,所以刪除所有的換行符

#對txt文件的換行符進(jìn)行刪除
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)

添加自定義詞語

此處可以根據(jù)自己的需要自定義,傳入的wordsByMyself是全局變量

分詞與詞頻統(tǒng)計(jì)

調(diào)用jieba進(jìn)行分詞,讀取通用詞表去掉停用詞(此步其實(shí)可以省略,對最終結(jié)果影響不大),將詞語和出現(xiàn)次數(shù)合成為鍵值對,輸出關(guān)鍵詞出現(xiàn)次數(shù)

#分詞并進(jìn)行詞頻統(tǒng)計(jì)
def cut_and_count(outPutTxt):
    with open(outPutTxt,encoding='utf-8') as f: 
        #step1:讀取文檔并調(diào)用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:統(tǒng)計(jì)特定關(guān)鍵詞的出現(xiàn)次數(shù)
        valuelist=[0]*len(wordsByMyself)
        counts=dict(zip(wordsByMyself,valuelist))
        for word in finalwords:
            if len(word) == 1:#單個(gè)詞不計(jì)算在內(nèi)
                continue
            else:
                counts[word]=counts.get(word,0)+1#遍歷所有詞語,每出現(xiàn)一次其對應(yīng)值加1
        for i in range(len(wordsByMyself)):
            if wordsByMyself[i] in counts:
                print(wordsByMyself[i]+':'+str(counts[wordsByMyself[i]]))
            else:
                print(wordsByMyself[i]+':0')

主函數(shù)

通過for循環(huán)進(jìn)行批量操作

if __name__ == "__main__":
    #rename()   
    for i in range(1,fileNum+1):
        pdf_to_txt('dealPdf\\'+str(i)+'.pdf',i)#將pdf文件轉(zhuǎn)化成txt文件,傳入文件路徑 
        delete_huanhangfu('dealTxt\\'+str(i)+'.txt',i)#對txt文件的換行符進(jìn)行刪除,防止詞語因換行被拆分
        word_by_myself()#添加自定義詞語
        print(f'----------result {i}----------')
        cut_and_count('outPutTxt\\'+str(i)+'.txt')#分詞并進(jìn)行詞頻統(tǒng)計(jì),傳入文件路徑

本地文件結(jié)構(gòu)

全部代碼

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=['社會(huì)責(zé)任','義務(wù)','上市','公司'] #自定義詞語,全局變量
fileNum=16#存儲(chǔ)總共待處理的文件數(shù)量

#重命名所有文件夾下的文件,適應(yīng)處理需要
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文件轉(zhuǎn)化成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轉(zhuǎn)換,不提供就忽略
    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是一個(gè)LTPage對象 里面存放著 這個(gè)page解析出的各種對象
                # 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等
                # 想要獲取文本就獲得對象的text屬性,
                for x in layout:
                    if isinstance(x, LTTextBoxHorizontal):
                        results = x.get_text()
                        fw.write(results)

#對txt文件的換行符進(jìn)行刪除
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])

#分詞并進(jìn)行詞頻統(tǒng)計(jì)
def cut_and_count(outPutTxt):
    with open(outPutTxt,encoding='utf-8') as f: 
        #step1:讀取文檔并調(diào)用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:統(tǒng)計(jì)特定關(guān)鍵詞的出現(xiàn)次數(shù)
        valuelist=[0]*len(wordsByMyself)
        counts=dict(zip(wordsByMyself,valuelist))
        for word in finalwords:
            if len(word) == 1:#單個(gè)詞不計(jì)算在內(nèi)
                continue
            else:
                counts[word]=counts.get(word,0)+1#遍歷所有詞語,每出現(xiàn)一次其對應(yīng)值加1
        for i in range(len(wordsByMyself)):
            if wordsByMyself[i] in counts:
                print(wordsByMyself[i]+':'+str(counts[wordsByMyself[i]]))
            else:
                print(wordsByMyself[i]+':0')

#主函數(shù) 
if __name__ == "__main__":
    rename()   
    for i in range(1,fileNum+1):
        pdf_to_txt('dealPdf\\'+str(i)+'.pdf',i)#將pdf文件轉(zhuǎn)化成txt文件,傳入文件路徑 
        delete_huanhangfu('dealTxt\\'+str(i)+'.txt',i)#對txt文件的換行符進(jìn)行刪除,防止詞語因換行被拆分
        word_by_myself()#添加自定義詞語
        print(f'----------result {i}----------')
        cut_and_count('outPutTxt\\'+str(i)+'.txt')#分詞并進(jìn)行詞頻統(tǒng)計(jì),傳入文件路徑

結(jié)果預(yù)覽

到此這篇關(guān)于python批量處理PDF文檔輸出自定義關(guān)鍵詞的出現(xiàn)次數(shù)的文章就介紹到這了,更多相關(guān)python處理PDF文檔內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何使用Python?VTK繪制線條

    如何使用Python?VTK繪制線條

    這篇文章主要介紹了如何使用Python-VTK繪制線條,主要繪制直線和曲線,下面文章詳細(xì)實(shí)現(xiàn)過程需要的小伙伴可以參考一下
    2022-04-04
  • 使用Python實(shí)現(xiàn)IP網(wǎng)絡(luò)掃描工具

    使用Python實(shí)現(xiàn)IP網(wǎng)絡(luò)掃描工具

    這篇文章主要為大家詳細(xì)介紹了如何使用Python實(shí)現(xiàn)一個(gè)IP網(wǎng)段掃描工具,可以輕松幫助你檢查每個(gè)網(wǎng)段下的IP是否在線,感興趣的可以了解下
    2025-01-01
  • python三引號(hào)如何輸入

    python三引號(hào)如何輸入

    在本篇文章里小編給大家整理的是關(guān)于python三引號(hào)輸入方法及相關(guān)實(shí)例,需要的朋友們可以學(xué)習(xí)下。
    2020-07-07
  • Python?Conda安裝包報(bào)錯(cuò):PackagesNotFoundError兩種解決方法

    Python?Conda安裝包報(bào)錯(cuò):PackagesNotFoundError兩種解決方法

    這篇文章主要給大家介紹了關(guān)于Python?Conda安裝包報(bào)錯(cuò):PackagesNotFoundError的兩種解決方法,這通常意味著安裝程序正在尋找的環(huán)境包沒有在 conda 的默認(rèn)通道中找到,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下
    2024-06-06
  • 分享3個(gè)非常實(shí)用的?Python?模塊

    分享3個(gè)非常實(shí)用的?Python?模塊

    這篇文章主要爹大家分享的是分享3個(gè)非常實(shí)用的?Python?模塊,知道的人可能不多,但是特別的好用,分別是Psutil、Pendulum、Pyfiglet三種模塊,需要的小伙伴可以參考下面相關(guān)內(nèi)容,希望對你有所幫助
    2022-03-03
  • 利用Python簡單的可視化工具

    利用Python簡單的可視化工具

    這篇文章講述了數(shù)據(jù)可視化的必要性,介紹了幾種常用的Python可視化庫(Matplotlib、Seaborn、Plotly、GeoPandas、Folium),并通過實(shí)例展示了如何使用這些庫進(jìn)行圖表繪制和分析
    2025-01-01
  • 淺談Pytorch 定義的網(wǎng)絡(luò)結(jié)構(gòu)層能否重復(fù)使用

    淺談Pytorch 定義的網(wǎng)絡(luò)結(jié)構(gòu)層能否重復(fù)使用

    這篇文章主要介紹了Pytorch定義的網(wǎng)絡(luò)結(jié)構(gòu)層能否重復(fù)使用的操作,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-06-06
  • python實(shí)現(xiàn)斐波那契數(shù)列的方法示例

    python實(shí)現(xiàn)斐波那契數(shù)列的方法示例

    每個(gè)碼農(nóng)大概都會(huì)用自己擅長的語言寫出一個(gè)斐波那契數(shù)列出來,斐波那契數(shù)列簡單地說,起始兩項(xiàng)為0和1,此后的項(xiàng)分別為它的前兩項(xiàng)之后。下面這篇文章就給大家詳細(xì)介紹了python實(shí)現(xiàn)斐波那契數(shù)列的方法,有需要的朋友們可以參考借鑒,下面來一起看看吧。
    2017-01-01
  • 手把手教你Python抓取數(shù)據(jù)并可視化

    手把手教你Python抓取數(shù)據(jù)并可視化

    很多小伙伴在提到python數(shù)據(jù)可視化的時(shí)候第一反應(yīng)就是matplotlib庫,但實(shí)際上python還有很多很好用的數(shù)據(jù)可視化的庫,下面這篇文章主要給大家介紹了關(guān)于如何利用Python抓取數(shù)據(jù)并可視化的相關(guān)資料,需要的朋友可以參考下
    2022-05-05
  • 利用Python開發(fā)Markdown表格結(jié)構(gòu)轉(zhuǎn)換為Excel工具

    利用Python開發(fā)Markdown表格結(jié)構(gòu)轉(zhuǎn)換為Excel工具

    在數(shù)據(jù)管理和文檔編寫過程中,我們經(jīng)常使用 Markdown 來記錄表格數(shù)據(jù),但它沒有Excel使用方便,所以本文將使用Python編寫一個(gè)轉(zhuǎn)換工具,希望對大家有所幫助
    2025-03-03

最新評(píng)論

金山区| 安图县| 祁门县| 都兰县| 沙雅县| 乌兰察布市| 轮台县| 乌鲁木齐县| 凤翔县| 镶黄旗| 汝南县| 乌苏市| 阿鲁科尔沁旗| 娱乐| 平泉县| 天津市| 苍梧县| 广宗县| 句容市| 云安县| 泽州县| 上杭县| 丁青县| 易门县| 桦甸市| 藁城市| 中西区| 工布江达县| 玉林市| 上栗县| 财经| 佛坪县| 武隆县| 辽宁省| 建德市| 龙川县| 连山| 古交市| 桂阳县| 湟源县| 嘉定区|