欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

 更新時(shí)間:2022年09月02日 14:47:53   作者:極客柒  
這篇文章主要為大家詳細(xì)介紹了如何利用Python語(yǔ)言實(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è)開(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)文章

  • django云端留言板實(shí)例詳解

    django云端留言板實(shí)例詳解

    這篇文章主要介紹了django云端留言板實(shí)例詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Pandas中MultiIndex選擇并提取任何行和列

    Pandas中MultiIndex選擇并提取任何行和列

    本文主要介紹了Pandas中MultiIndex選擇并提取任何行和列,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-02-02
  • Python光學(xué)仿真wxpython之DC繪圖

    Python光學(xué)仿真wxpython之DC繪圖

    這篇文章主要為大家介紹了Python光學(xué)仿真wxpython之DC繪圖的基本概念及用法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-10-10
  • Python?pickle模塊實(shí)現(xiàn)Python對(duì)象持久化存儲(chǔ)

    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-05
  • python 基于opencv 繪制圖像輪廓

    python 基于opencv 繪制圖像輪廓

    這篇文章主要介紹了python 基于opencv 繪制圖像輪廓的示例,幫助大家更好的利用python的opencv庫(kù)處理圖像,感興趣的朋友可以了解下
    2020-12-12
  • Linux下用Python腳本監(jiān)控目錄變化代碼分享

    Linux下用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è)模型

    這篇文章主要介紹了用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
  • PyCharm添加python庫(kù)的方法步驟

    PyCharm添加python庫(kù)的方法步驟

    在使用PyCharm過(guò)程中,有時(shí)候需要添加需要的Python擴(kuò)展庫(kù),本文主要介紹了PyCharm添加python庫(kù)的方法步驟,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-03-03
  • 只需要100行Python代碼就可以實(shí)現(xiàn)的貪吃蛇小游戲

    只需要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-05
  • python 點(diǎn)云地面點(diǎn)濾波-progressive TIN densification(PTD)算法介紹

    python 點(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

最新評(píng)論