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

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > python >内容正文

python

Python读取PDF文档并翻译

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

更新:推薦大家用“趣卡翻譯”,非常好用,是本文原本想要實現(xiàn)的效果!!!

------------------------------------------------------------------------------------------------------

翻譯服務(wù)選擇免費的百度翻譯api:百度翻譯開放平臺

標準版服務(wù)完全免費,不限使用字符量

完成身份認證,還可免費升級至高級版、尊享版,每月享受200萬免費字符量及增值服務(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 = '' # !!!!補充secretKey = '' # !!!!補充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對象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文件,獲取文件中包含的各種對象 '''# 解析pdf文件函數(shù) def parse(pdf_path):textName = pdf_path.split('\\')[-1].split('.')[0] + '.txt'fp = open(pdf_path, 'rb') # 以二進制讀模式打開# 用文件對象來創(chuàng)建一個pdf文檔分析器parser = PDFParser(fp)# 創(chuàng)建一個PDF文檔doc = PDFDocument(parser)# 連接分析器 與文檔對象# parser.set_document(doc)# doc.set_parser(parser)# 提供初始化密碼# 如果沒有密碼 就創(chuàng)建一個空的字符串# doc.initialize()# 檢測文檔是否提供txt轉(zhuǎn)換,不提供就忽略if not doc.is_extractable:raise PDFTextExtractionNotAllowedelse:# 創(chuàng)建PDf 資源管理器 來管理共享資源rsrcmgr = PDFResourceManager()# 創(chuàng)建一個PDF設(shè)備對象laparams = LAParams()device = PDFPageAggregator(rsrcmgr, laparams=laparams)# 創(chuàng)建一個PDF解釋器對象interpreter = PDFPageInterpreter(rsrcmgr, device)# 用來計數(shù)頁面,圖片,曲線,figure,水平文本框等對象的數(shù)量num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0# 循環(huán)遍歷列表,每次處理一個page的內(nèi)容for page in PDFPage.create_pages(doc): # doc.get_pages() 獲取page列表num_page += 1 # 頁面增一print("\r\n>> 當(dāng)前頁:", num_page)interpreter.process_page(page)# 接受該頁面的LTPage對象layout = device.get_result()for x in layout:if isinstance(x,LTImage): # 圖片對象num_image += 1if isinstance(x,LTCurve): # 曲線對象num_curve += 1if isinstance(x,LTFigure): # figure對象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('對象數(shù)量:\n','頁面數(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)

運行中:

pdf轉(zhuǎn)txt:

翻譯:

總結(jié)

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

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