Python读取PDF文档并翻译
生活随笔
收集整理的這篇文章主要介紹了
Python读取PDF文档并翻译
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
更新:推薦大家用“趣卡翻譯”,非常好用,是本文原本想要實(shí)現(xiàn)的效果!!!
------------------------------------------------------------------------------------------------------
翻譯服務(wù)選擇免費(fèi)的百度翻譯api:百度翻譯開(kāi)放平臺(tái)
標(biāo)準(zhǔn)版服務(wù)完全免費(fèi),不限使用字符量
完成身份認(rèn)證,還可免費(fèi)升級(jí)至高級(jí)版、尊享版,每月享受200萬(wàn)免費(fèi)字符量及增值服務(wù)
# -*- coding: utf-8 -*-import random import hashlib import sys import importlib importlib.reload(sys) import timefrom pdfminer.pdfparser import PDFParser from pdfminer.pdfdocument import PDFDocument from pdfminer.pdfpage import PDFTextExtractionNotAllowed from pdfminer.pdfpage import PDFPagefrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import PDFPageAggregator from pdfminer.layout import *#**********翻譯部分******************** def fanyi(query):import http.clientimport hashlibimport urllibimport randomimport jsonappid = '' # !!!!補(bǔ)充secretKey = '' # !!!!補(bǔ)充httpClient = Nonemyurl = '/api/trans/vip/translate'q = queryfromLang = 'auto'toLang = 'zh'salt = random.randint(32768, 65536)sign = appid + q + str(salt) + secretKeym1 = hashlib.md5()m1.update(sign.encode())sign = m1.hexdigest()myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign# print(urllib.parse.quote(q))try:httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')httpClient.request('GET', myurl)# response是HTTPResponse對(duì)象response = httpClient.getresponse()html = response.read() # bytes# print("html: ",type(html),html)html_str = html.decode() # bytes to str# print("html_str: ",type(html_str),html_str)html_dict = json.loads(html_str) # str to dict# print("html_dist: ",type(html_dict),html_str)# result_ori = html_dict["trans_result"][0]["src"]# result_tar = html_dict["trans_result"][0]["dst"]# print(html_dict["trans_result"])result_tar = ''for i in html_dict["trans_result"]:result_tar += i["dst"]# print(result_ori, " --> ", result_tar)print("翻譯文本: " + result_tar)print("*" * 100)return result_tarexcept Exception as e:print(e)return ''finally:if httpClient:httpClient.close()''' 解析pdf文件,獲取文件中包含的各種對(duì)象 '''# 解析pdf文件函數(shù) def parse(pdf_path):textName = pdf_path.split('\\')[-1].split('.')[0] + '.txt'fp = open(pdf_path, 'rb') # 以二進(jìn)制讀模式打開(kāi)# 用文件對(duì)象來(lái)創(chuàng)建一個(gè)pdf文檔分析器parser = PDFParser(fp)# 創(chuàng)建一個(gè)PDF文檔doc = PDFDocument(parser)# 連接分析器 與文檔對(duì)象# parser.set_document(doc)# doc.set_parser(parser)# 提供初始化密碼# 如果沒(méi)有密碼 就創(chuàng)建一個(gè)空的字符串# doc.initialize()# 檢測(cè)文檔是否提供txt轉(zhuǎn)換,不提供就忽略if not doc.is_extractable:raise PDFTextExtractionNotAllowedelse:# 創(chuàng)建PDf 資源管理器 來(lái)管理共享資源rsrcmgr = PDFResourceManager()# 創(chuàng)建一個(gè)PDF設(shè)備對(duì)象laparams = LAParams()device = PDFPageAggregator(rsrcmgr, laparams=laparams)# 創(chuàng)建一個(gè)PDF解釋器對(duì)象interpreter = PDFPageInterpreter(rsrcmgr, device)# 用來(lái)計(jì)數(shù)頁(yè)面,圖片,曲線,figure,水平文本框等對(duì)象的數(shù)量num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0# 循環(huán)遍歷列表,每次處理一個(gè)page的內(nèi)容for page in PDFPage.create_pages(doc): # doc.get_pages() 獲取page列表num_page += 1 # 頁(yè)面增一print("\r\n>> 當(dāng)前頁(yè):", num_page)interpreter.process_page(page)# 接受該頁(yè)面的LTPage對(duì)象layout = device.get_result()for x in layout:if isinstance(x,LTImage): # 圖片對(duì)象num_image += 1if isinstance(x,LTCurve): # 曲線對(duì)象num_curve += 1if isinstance(x,LTFigure): # figure對(duì)象num_figure += 1if isinstance(x, LTTextBoxHorizontal): # 獲取文本內(nèi)容num_TextBoxHorizontal += 1 # 水平文本框?qū)ο笤鲆籸esults = x.get_text()print(results.replace('\n', ''))# 保存文本內(nèi)容with open(textName, 'a+', encoding='utf8') as f:results = x.get_text()f.write(results.replace('\n', '') + '\n')print('對(duì)象數(shù)量:\n','頁(yè)面數(shù):%s\n'%num_page,'圖片數(shù):%s\n'%num_image,'曲線數(shù):%s\n'%num_curve,'水平文本框:%s\n'%num_TextBoxHorizontal)import os if __name__ == '__main__':pdf_path = r'1803.08494.pdf'rootPath = '\\'.join(pdf_path.split('\\')[:-1]) if "\\" in pdf_path else ''textName = pdf_path.split('\\')[-1].split('.')[0] + '.txt'print(">> 當(dāng)前文件:", os.path.join(rootPath, textName))if os.path.exists(os.path.join(rootPath, textName)):print(">> 刪除:", textName)os.remove(os.path.join(rootPath, textName))if os.path.exists(os.path.join(rootPath, "translate.txt")):print(">> 刪除:", "translate.txt")os.remove(os.path.join(rootPath, "translate.txt"))parse(pdf_path)with open(textName, 'r', encoding='utf8') as f:content = f.read()results = content.split('.')for i in results:res = fanyi(i)with open("translate.txt", 'a+', encoding='utf8') as fp:fp.write(res + '\n')time.sleep(1)運(yùn)行中:
pdf轉(zhuǎn)txt:
翻譯:
總結(jié)
以上是生活随笔為你收集整理的Python读取PDF文档并翻译的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 计算机网络常用知识笔记(超全面)!
- 下一篇: python灰色模型代码_几行代码搞定M