Python實(shí)現(xiàn)批量翻譯的示例代碼
截圖
源碼
Translator.py
#!/usr/bin/python # -*- coding: UTF-8 -*- from copy import deepcopy from distutils.log import Log from email import utils import json import http.client #修改引用的模塊 import hashlib from msilib import Table from multiprocessing.dummy import Array from operator import index, truediv from tokenize import group from turtle import st #修改引用的模塊 from urllib import parse import random from Log import Debug # 百度注冊(cè)開(kāi)發(fā)者 并創(chuàng)建通用翻譯 使用高級(jí)翻譯app應(yīng)用接口 獲取 appid和secretKey # 百度開(kāi)發(fā)使用的api接口 翻譯的句子會(huì)比 游客身份翻譯的結(jié)果 更準(zhǔn)確 appid = '20220829001324165' #你的appid 這里可以先用我的試用一下 secretKey = 'owSrQDeWHGPvI0U1BUm8' #你的密鑰 singleTranslteMaxCount = 3 #單個(gè)單詞翻譯失敗次數(shù)的上限 class WordInformation: _reqCount = None _from = None _to = None _text = None _translateText = None _nextWorld = None def __init__(self, text:str,fromLanguage:str,toLanguage:str,nextWorld) -> None: self._reqCount = 0 self._text = text self._from = fromLanguage self._to = toLanguage self._nextWorld = nextWorld def CanReq(self): if self._reqCount > singleTranslteMaxCount: return False self._reqCount += 1 return True def GetText(self): return self._text def GetTranslateText(self): if None != self._translateText: return self._translateText return self._text def GetNext(self): return self._nextWorld def Translater( worldInfo:WordInformation): if worldInfo == None: return Debug.Log(f"{worldInfo.GetText()} 正在翻譯...") myurl = '/api/trans/vip/translate' q = worldInfo.GetText() fromLang = worldInfo._from toLang = worldInfo._to salt = random.randint(32768, 65536) sign = appid+q+str(salt)+secretKey m1 = hashlib.md5() m1.update(sign.encode("utf-8")) sign = m1.hexdigest() myurl = myurl+'?appid='+appid+'&q='+parse.quote(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign httpClient = http.client.HTTPConnection('api.fanyi.baidu.com') httpClient.request('GET', myurl) response = httpClient.getresponse() #轉(zhuǎn)碼 html = response.read().decode('utf-8') html = json.loads(html) if httpClient: httpClient.close() if "trans_result" in html: dst = html["trans_result"][0]["dst"] worldInfo._translateText = dst # Translater(worldInfo.GetNext()) # else: # if worldInfo.CanReq(): # Translater(worldInfo) # else: # Translater(worldInfo.GetNext()) def GetWorldInfoArrByTextArr( texts:Array,fromLanguage:str,toLanguage:str ): num = len(texts) worlds = [] for i in range(num-1,0,-1): if i == num - 1: world = WordInformation(texts[i],fromLanguage,toLanguage,None) worlds.append(world) else: world = WordInformation(texts[i],fromLanguage,toLanguage,worlds[len(worlds)-1]) worlds.append(world) return worlds def Translation( needTranslateTexts:Array,fromLanguage:str,toLanguage:str ): worlds = GetWorldInfoArrByTextArr(needTranslateTexts,fromLanguage,toLanguage) Debug.Runtime("翻譯用時(shí): ") # 遞推方式 next指針不為none 遞歸執(zhí)行next # Translater(worlds[len(worlds)-1]) # 迭代方式 for i in range(0,len(worlds)): Translater(worlds[i]) if worlds[i].GetTranslateText() == None and worlds[i].CanReq(): i -= 1 Debug.Runtime("翻譯用時(shí): ") worlds.reverse() translateTexts = [ ] for world in worlds: translateTexts.append(world.GetTranslateText()) return translateTexts,worlds
Log.py
import sys import time import traceback import Utils DEBUG = True #if sys.gettrace() else False class Debug: __log = '' __time = dict() @staticmethod def Log(textContent:str): ''' 輸出日志 DEBUG模式下 同時(shí)輸出編輯器顯示 ''' times = time.time() local_time = time.localtime(times) tstr = time.strftime("%Y-%m-%d %H:%M:%S",local_time) str1 = f"{tstr}\t{textContent}\n" if DEBUG: print(str1) Debug.__log += str1 @staticmethod def LogExcept(): ''' 輸出堆棧信息 一般用于捕獲異常報(bào)錯(cuò)后調(diào)用 ''' Debug.Log(traceback.format_exc()) @staticmethod def Runtime(str1): ''' 輸出兩次打印間程序的運(yùn)行時(shí)間 成雙成對(duì)的方式出現(xiàn) 第一次調(diào)用并不會(huì)打印任何信息 僅在第二次調(diào)用后 返回與第一調(diào)用間的間隔 ''' if(str1 in Debug.__time.keys()): runtime = time.time() - Debug.__time[str1] del Debug.__time[str1] Debug.Log("%s%f秒"%(str1,runtime)) else: Debug.__time[str1] = time.time() @staticmethod def Output(): Utils.writeInFile('./log.txt', Debug.__log)
Utils.py
''' 工具類 ''' import base64 import json # json相關(guān) import os # 文件流相關(guān) import zipfile # zip亞索文件 import shutil # 刪除整個(gè)文件夾 def fromFile(url): try: with open(url, 'r', encoding='utf-8') as fp: return fp.read() finally: fp.close() def fromFile2Base64(url): try: with open(url, 'rb') as f1: return str(base64.b64encode(f1.read()), encoding='utf-8') finally: f1.close() def writeInFile(toFile, content): try: with open(toFile, 'w', encoding='utf-8') as fp: fp.write(content) finally: fp.close() def fromJsonAsDict(url): return json.loads((fromFile(url))) def writeDictInFile(url, dict1): writeInFile(url, json.dumps(dict1, ensure_ascii=False, indent=2)) def revealInFileExplorer(targetDir): try: os.startfile(targetDir) except: os.system("explorer.exe %s" % targetDir) def zipFile(src, dest): ''' src: 目標(biāo)文件位置 D:/123.txt dest: 壓縮后輸出的zip路徑 D:/123.zip ''' with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as p: p.write(src,os.path.split(src)[1]) p.close() def zipFiles(src,dest): ''' src: 目標(biāo)文件夾位置 D:/hellowd dest: 壓縮后輸出的zip路徑 D:/hellowd.zip ''' with zipfile.ZipFile(dest, 'w',zipfile.ZIP_DEFLATED) as pZip: for folder, _, files in os.walk(src): relative_url = folder.replace(src, '') for file in files: pZip.write(os.path.join(folder,file),os.path.join(relative_url,file)) pZip.close() def removeFile(url): if os.path.isdir(url): shutil.rmtree(url) else: os.remove(url)
簡(jiǎn)單的使用案例
# 導(dǎo)入Translation from Translator import Translation zhTexts = ["為了解決商家的讓利活動(dòng)我壓力很大。","為了解決商家的讓利活動(dòng)我壓力很大。","消耗{0}體力","獲取{0}鈔票" ] enTexts,enWorlds = Translation(zhTexts,'zh','en') print(enTexts)
Python版本
python 3.99
可兼容版本 3.x
到此這篇關(guān)于Python實(shí)現(xiàn)批量翻譯的示例代碼的文章就介紹到這了,更多相關(guān)Python批量翻譯內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python?pickle模塊實(shí)現(xiàn)Python對(duì)象持久化存儲(chǔ)
這篇文章主要介紹了Python?pickle模塊實(shí)現(xiàn)Python對(duì)象持久化存儲(chǔ),pickle?是?python?語(yǔ)言的一個(gè)標(biāo)準(zhǔn)模塊,和python安裝時(shí)共同安裝好的一個(gè)模塊。下文基于pickle模塊展開(kāi)實(shí)現(xiàn)Python對(duì)象持久化存儲(chǔ)的詳細(xì)內(nèi)容,需要的朋友可以參考一下2022-05-05Linux下用Python腳本監(jiān)控目錄變化代碼分享
這篇文章主要介紹了Linux下用Python腳本監(jiān)控目錄變化代碼分享,本文直接給出實(shí)現(xiàn)代碼,需要的朋友可以參考下2015-05-05如何用Pytorch搭建一個(gè)房?jī)r(jià)預(yù)測(cè)模型
這篇文章主要介紹了用Pytorch搭建一個(gè)房?jī)r(jià)預(yù)測(cè)模型,在這里我將主要討論P(yáng)yTorch建模的相關(guān)方面,作為一點(diǎn)額外的內(nèi)容,我還將演示PyTorch中開(kāi)發(fā)的模型的神經(jīng)元重要性,需要的朋友可以參考下2023-03-03只需要100行Python代碼就可以實(shí)現(xiàn)的貪吃蛇小游戲
貪吃蛇小游戲相信80、90后小時(shí)候肯定都玩過(guò),那么你知道如果通過(guò)Python來(lái)實(shí)現(xiàn)嗎?今天就來(lái)教大家,文中有非常詳細(xì)的代碼示例,對(duì)正在學(xué)習(xí)python的小伙伴們很有幫助,需要的朋友可以參考下2021-05-05python 點(diǎn)云地面點(diǎn)濾波-progressive TIN densification(PTD)算法介紹
關(guān)于地面點(diǎn)濾波的概念我們要與孤立點(diǎn)(outlier)濾波區(qū)分開(kāi),孤立點(diǎn)濾波可以理解為圖像中的去噪,去除數(shù)據(jù)測(cè)量過(guò)程中受到飛鳥(niǎo)、多路徑效應(yīng)所產(chǎn)生的遠(yuǎn)低于/高于其他數(shù)據(jù)的點(diǎn)。今天通過(guò)本文給大家分享python PTD點(diǎn)云地面點(diǎn)濾波的相關(guān)知識(shí),一起看看吧2021-08-08