Python读取PDF文档并翻译

自制文档翻译小工具,告别xxx词典的收费翻译!
翻译服务选择免费的百度翻译api
https://api.fanyi.baidu.com/标准版服务完全免费,不限使用字符量完成身份认证,还可免费升级至高级版、尊享版 , 每月享受200万免费字符量及增值服务
Python读取PDF文档并翻译

# -*- coding: utf-8 -*- import randomimport hashlibimport sysimport importlibimportlib.reload(sys)import timefrom pdfminer.pdfparser import PDFParser,PDFDocumentfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreterfrom pdfminer.converter import PDFPageAggregatorfrom pdfminer.layout import *from pdfminer.pdfinterp import PDFTextExtractionNotAllowed#**********翻译部分********************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 = appidqstr(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文件函数def parse(pdf_path):textName = pdf_path.split('\')[-1].split('.')[0]'.txt'fp = open(pdf_path, 'rb')# 以二进制读模式打开# 用文件对象来创建一个pdf文档分析器parser = PDFParser(fp)# 创建一个PDF文档doc = PDFDocument()# 连接分析器 与文档对象parser.set_document(doc)doc.set_parser(parser)# 提供初始化密码# 如果没有密码 就创建一个空的字符串doc.initialize()# 检测文档是否提供txt转换 , 不提供就忽略if not doc.is_extractable:raise PDFTextExtractionNotAllowedelse:# 创建PDf 资源管理器 来管理共享资源rsrcmgr = PDFResourceManager()# 创建一个PDF设备对象laparams = LAParams()device = PDFPageAggregator(rsrcmgr, laparams=laparams)# 创建一个PDF解释器对象interpreter = PDFPageInterpreter(rsrcmgr, device)# 用来计数页面,图片,曲线,figure,水平文本框等对象的数量num_page, num_image, num_curve, num_figure, num_TextBoxHorizontal = 0, 0, 0, 0, 0# 循环遍历列表 , 每次处理一个page的内容for page in doc.get_pages(): # doc.get_pages() 获取page列表num_page= 1# 页面增一print("rn>> 当前页:", 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):# 获取文本内容num_TextBoxHorizontal= 1# 水平文本框对象增一results = x.get_text()print(results.replace('n', ''))# 保存文本内容with open(textName, 'a ', encoding='utf8') as f:results = x.get_text()f.write(results.replace('n', '')'n')print('对象数量:n','页面数:%sn'%num_page,'图片数:%sn'%num_image,'曲线数:%sn'%num_curve,'水平文本框:%sn'%num_TextBoxHorizontal) import osif __name__ == '__main__':pdf_path = r'A Survey on Network Methodologies for.pdf'rootPath = '\'.join(pdf_path.split('\')[:-1]) if "\" in pdf_path else ''textName = pdf_path.split('\')[-1].split('.')[0]'.txt'print(">> 当前文件:", 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)
运行中:
Python读取PDF文档并翻译

【Python读取PDF文档并翻译】pdf转txt:
Python读取PDF文档并翻译

翻译:
Python读取PDF文档并翻译



pdf转文字问题、分句问题,翻译结果可能不准,仅供参考 。

相关经验推荐