最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)批量翻譯的示例代碼

 更新時(shí)間:2022年09月02日 14:47:53   作者:極客柒  
這篇文章主要為大家詳細(xì)介紹了如何利用Python語言實(shí)現(xiàn)批量翻譯的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

截圖

源碼

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è)開發(fā)者 并創(chuàng)建通用翻譯 使用高級(jí)翻譯app應(yīng)用接口 獲取 appid和secretKey
# 百度開發(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實(shí)現(xiàn)截取PDF文件中的幾頁代碼實(shí)例

    Python實(shí)現(xiàn)截取PDF文件中的幾頁代碼實(shí)例

    今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)截取PDF文件中的幾頁代碼實(shí)例,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • python中int與str互轉(zhuǎn)方法

    python中int與str互轉(zhuǎn)方法

    最近學(xué)習(xí)python中的數(shù)據(jù)類型時(shí),難免聯(lián)想到j(luò)ava中的基本型數(shù)據(jù)類型與引用型數(shù)據(jù)類型。接下來通過本文給大家介紹python中int與str互轉(zhuǎn),需要的朋友可以參考下
    2018-07-07
  • 完美解決ARIMA模型中plot_acf畫不出圖的問題

    完美解決ARIMA模型中plot_acf畫不出圖的問題

    這篇文章主要介紹了完美解決ARIMA模型中plot_acf畫不出圖的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • Pytorch Tensor 輸出為txt和mat格式方式

    Pytorch Tensor 輸出為txt和mat格式方式

    今天小編就為大家分享一篇Pytorch Tensor 輸出為txt和mat格式方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • Python turtle畫圖庫&&畫姓名實(shí)例

    Python turtle畫圖庫&&畫姓名實(shí)例

    今天小編就為大家分享一篇Python turtle畫圖庫&&畫姓名實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python數(shù)組如何添加整行或整列

    python數(shù)組如何添加整行或整列

    這篇文章主要介紹了python數(shù)組如何添加整行或整列問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-01-01
  • Python實(shí)現(xiàn)Mysql全量數(shù)據(jù)同步的腳本分享

    Python實(shí)現(xiàn)Mysql全量數(shù)據(jù)同步的腳本分享

    這篇文章主要為大家詳細(xì)介紹了基于Python如何實(shí)現(xiàn)Mysql全量數(shù)據(jù)同步的功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起了解一下
    2023-06-06
  • python密碼學(xué)RSA密碼解密教程

    python密碼學(xué)RSA密碼解密教程

    這篇文章主要為大家介紹了python密碼學(xué)RSA密碼解密教程,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-05-05
  • Python實(shí)現(xiàn)的txt文件去重功能示例

    Python實(shí)現(xiàn)的txt文件去重功能示例

    這篇文章主要介紹了Python實(shí)現(xiàn)的txt文件去重功能,涉及Python針對(duì)txt文本文件的讀寫、字符串遍歷、判斷相關(guān)操作技巧,需要的朋友可以參考下
    2018-07-07
  • Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)保存最后N個(gè)元素的方法

    Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)保存最后N個(gè)元素的方法

    這篇文章主要介紹了Python數(shù)據(jù)結(jié)構(gòu)與算法 保存最后N個(gè)元素的方法,涉及Python基于迭代器與生成器實(shí)現(xiàn)歷史記錄功能的相關(guān)操作技巧,需要的朋友可以參考下
    2018-02-02

最新評(píng)論

鹤峰县| 固安县| 大方县| 滦平县| 泸水县| 肇州县| 承德市| 河间市| 正阳县| 临清市| 牡丹江市| 万源市| 陆丰市| 南充市| 枣庄市| 庐江县| 秀山| 南江县| 浦江县| 肃北| 观塘区| 沐川县| 靖江市| 鸡泽县| 乐昌市| 吴桥县| 达州市| 苏尼特右旗| 黄龙县| 富顺县| 延庆县| 平昌县| 怀柔区| 四平市| 寿阳县| 颍上县| 米易县| 江达县| 大名县| 来安县| 醴陵市|