日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python读取pdf翻译生成word

發(fā)布時間:2023/12/10 python 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python读取pdf翻译生成word 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

python讀取pdf翻譯生成word文件


對應python版本未3.7.3
首先是安裝所需要的包
通過pip安裝或是pycharm的setting安裝
這里僅列出包名(tkinter requests time hashlib json os pdfminer docx)

在運行程序前需要先注冊一個百度翻譯的api
設置api_id、cyber

這里注冊普通的接口就足夠使用

import tkinter import requests import time import hashlib import json import os import docx from tkinter.filedialog import askdirectory from tkinter.messagebox import * from pdfminer.pdfparser import PDFParser, PDFDocument from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LAParams,LTTextBox##初始化api_url = "http://api.fanyi.baidu.com/api/trans/vip/translate" api_id = " " ##申請的百度翻譯接口的id cyber = " " ##申請的百度翻譯接口的passwordfile = "multinet.pdf" ##處理的pdf##存儲提取的txt CNtextfile = "CNmultinet.txt" ##存儲翻譯的結果 isTranslate = True ##是否將提取的英文翻譯為中文#生成界面 root=tkinter.Tk() root.geometry('500x250') root.title('翻譯小程序') #定義讀取本地路徑函數(shù) def selectPath1():path_ = askdirectory()pathroad1.set(path_) def selectPath2():path_ = askdirectory()pathroad2.set(path_)#生成文本框 pathroad1=tkinter.StringVar()#設置pathroad為輸入文本 b1entry=tkinter.Entry(root,width=500,textvariable=pathroad1)#為輸入文本的功能設計文本框 b1entry.place(x=100,y=60,width=300,height=20)pathroad2=tkinter.StringVar()#設置pathroad為輸入文本 b2entry=tkinter.Entry(root,width=500,textvariable=pathroad2)#為輸入文本的功能設計文本框 b2entry.place(x=100,y=80,width=300,height=20)#定義中間文件及函數(shù) ENtextfile=b1entry.get()+'ENtextfile' ## 處理PDF ## 讀取PDF的內(nèi)容 filename是待處理的PDF的名字 ###使用PDFminer讀取 def getDataUsingPyPDF(file):parser = PDFParser(open(file, 'rb')) # 以二進制打開文件 ,并創(chuàng)建一個pdf文檔分析器doc = PDFDocument() ##創(chuàng)建一個pdf文檔# 將文檔對象和連接分析器連接起來parser.set_document(doc)doc.set_parser(parser)doc.initialize()# 判斷該pdf是否支持txt轉(zhuǎn)換if doc.is_extractable:# 創(chuàng)建一個PDF設備對象rsrcmgr = PDFResourceManager()# 創(chuàng)建一個pdf設備對象laparamas = LAParams()device = PDFPageAggregator(rsrcmgr, laparams=laparamas)# 創(chuàng)建一個PDF解釋器對象interpreter = PDFPageInterpreter(rsrcmgr, device)contents = "" # 保存讀取的text# 依次讀取每個page的內(nèi)容for page in doc.get_pages():interpreter.process_page(page)layout = device.get_result() # 這里layout是一個LTPage對象 里面存放著 這個page解析出的各種對象 一般包括LTTextBox, LTFigure, LTImage, LTTextBoxHorizontal 等等 想要獲取文本就獲得對象的text屬性,# 在windows下,新文件的默認編碼是gbk編碼,所以我們在寫入文件的時候需要設置一個編碼格式,如下:for x in layout:if (isinstance(x, LTTextBox)):results = x.get_text()contents += (results)saveText( contents,ENtextfile)return contents## 將讀取的content以txt格式存放到 def saveText(content, Textfile):with open(Textfile, "w", encoding='utf-8') as f:f.write(content) ##將讀取的 def savedoc(content, docfile):doc = docx.Document() # 創(chuàng)建一個Document對象doc.add_paragraph(content) # 增加一個paragraphdoc.save( docfile+'.docx')#文字的排版,去掉多余換行符及字數(shù)過少的行 def adjust(text):f =open(text,encoding='UTF-8', errors = 'ignore')lines = f.readlines()string = ""for line in lines:if len(line)<8 and line[-1]=='\n':#字母少于8則刪去passelif line[-1] == '\n' and line[-2]=='.':#句尾是.和回車則保留回車string += lineelse:string += line[:-1]#去掉句尾回車return string## 翻譯從pdf提取的content def translate(content):salt = str(time.time())[:10]final_sign = str(api_id) + content + salt + cyberfinal_sign = hashlib.md5(final_sign.encode("utf-8")).hexdigest()paramas = {'q': content,'from': 'en','to': 'zh','appid': '%s' % api_id,'salt': '%s' % salt,'sign': '%s' % final_sign}my_url = api_url + '?appid=' + str(api_id) + '&q=' + content + '&from=' + 'zh' + '&to=' + 'en' + '&salt=' + salt + '&sign=' + final_signresponse = requests.get(api_url, params=paramas).contentcontent = str(response, encoding="utf-8")json_reads = json.loads(content)return json_reads['trans_result'][0]['dst'] + "\n"#定義按鈕處理函數(shù) def fanyi():PDFlist=b1entry.get()TXTlist=b2entry.get()for filename in os.listdir(PDFlist):outfile = filename[:-4] + '.docx'print(outfile)file=PDFlist+'\\'+filenamecontents = getDataUsingPyPDF(file)contents=adjust(ENtextfile)if (isTranslate):clist = contents.split("\n") # split() 通過指定.將英文分成多個句子i = 0chinese = ""outfile = TXTlist + '\\' + outfilewhile (i < clist.__len__()):print(i) # 22try:chinese += (translate(clist[i]))time.sleep(0.5)#設置等待時間except:print("Current failed: " + str(i))i += 1#saveText(chinese, outfile)savedoc(chinese,outfile)showinfo('提示', '翻譯完成')##生成按鈕 b1=tkinter.Button(root,text='PDF文件夾',command = selectPath1)#生成文本提示詞 #b1.pack(side=tkinter.LEFT)#將b1添加至主窗口 b1.place(x=20,y=60,width=70,height=20)b2=tkinter.Button(root,text='txt文件夾',command = selectPath2)# #b2.pack(side=tkinter.LEFT)#將b1添加至主窗口 b2.place(x=20,y=80,width=70,height=20)work=tkinter.Button(root,text='翻譯',command=fanyi)#生成翻譯鍵 work.pack(side=tkinter.LEFT)#將b1添加至主窗口 work.place(x=200,y=120,width=70,height=20)root.mainloop()#進入消息循環(huán) ######

程序運行成功會出現(xiàn)下圖界面

這里要注意的是文件夾不會顯示里面的文件,pdf文件夾選擇時里面一定要只有pdf文件且沒有密碼。選擇完路徑后點擊翻譯就可以了。

生成的word排版存在一些問題,可以在adjust函數(shù)再加一些限制,或者讀取pdf時識別它的排版,這些暫時未能解決。

總結

以上是生活随笔為你收集整理的python读取pdf翻译生成word的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。