SoFunction
Updated on 2024-11-12

Python sample code to achieve batch translation

screenshot (computing)

source code (computing)

#!/usr/bin/python
# -*- coding: UTF-8 -*-

from copy import deepcopy
from  import Log
from email import utils
import json
import   # Modify referenced modules
import hashlib
from msilib import Table
from  import Array
from operator import index, truediv
from tokenize import group
from turtle import st    # Modify referenced modules
from urllib import parse
import random
from Log import Debug

# Baidu Register as a developer and create Universal Translator Use the Advanced Translator app application interface to get appid and secretKey
# The api interface used by baidu developers will translate sentences more accurately than the results of a guest ID translation.
appid = '20220829001324165' #Your appid, you can try mine here.
secretKey = 'owSrQDeWHGPvI0U1BUm8' # Your key
singleTranslteMaxCount = 3 # of failed translations for a single word

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
    (f"{()} Translation in progress....")
    myurl = '/api/trans/vip/translate'
    q = ()
    fromLang = worldInfo._from
    toLang = worldInfo._to
    salt = (32768, 65536)

    sign = appid+q+str(salt)+secretKey
    m1 = hashlib.md5()
    (("utf-8"))
    sign = ()
    myurl = myurl+'?appid='+appid+'&q='+(q)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign
    httpClient = ('')
    ('GET', myurl)
    response = ()
    #Transcoding
    html = ().decode('utf-8')
    html = (html)

    if httpClient:
        ()
    
    if "trans_result" in html:
        dst = html["trans_result"][0]["dst"]
        worldInfo._translateText = dst
        # Translater(())
    # else:
    #     if ():
    #         Translater(worldInfo)
    #     else:
    #         Translater(())

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)
            (world)
        else:
            world = WordInformation(texts[i],fromLanguage,toLanguage,worlds[len(worlds)-1])
            (world)
    return worlds

def Translation( needTranslateTexts:Array,fromLanguage:str,toLanguage:str ):
    worlds = GetWorldInfoArrByTextArr(needTranslateTexts,fromLanguage,toLanguage)
    
    ("Translation time:")
    # recursive way next pointer is not none recursive execution next
    # Translater(worlds[len(worlds)-1])
    # Iterative approach
    for i in range(0,len(worlds)):
        Translater(worlds[i])
        if worlds[i].GetTranslateText() == None and worlds[i].CanReq():
            i -= 1
    ("Translation time:")

    ()
    translateTexts = [ ]
    for world in worlds:
        (())
    return translateTexts,worlds

import sys
import time
import traceback
import Utils

DEBUG = True #if () else False

class Debug:
    __log = ''
    __time = dict()
    @staticmethod
    def Log(textContent:str):
        '''
            Output log DEBUG mode Simultaneous output editor display
        '''
        times = ()
        local_time = (times)
        tstr = ("%Y-%m-%d %H:%M:%S",local_time)
        str1 = f"{tstr}\t{textContent}\n"
        if DEBUG:
            print(str1)
        Debug.__log += str1

    @staticmethod
    def LogExcept():
        '''
            Outputs stack information Typically called after an exception is caught and an error is reported.
        '''
        (traceback.format_exc())

    @staticmethod
    def Runtime(str1):
        '''
            Outputs the running time of the program between prints
            Appears in pairs

            The first call does not print anything
            Only after the second call, the interval between the first call and the first call is returned.
        '''
        if(str1 in Debug.__time.keys()):
            runtime = () - Debug.__time[str1]
            del Debug.__time[str1]
            ("%s%f seconds."%(str1,runtime))
        else:
            Debug.__time[str1] = ()

    @staticmethod
    def Output():
        ('./', Debug.__log)

'''
    Tools

'''

import base64
import json  # json related
import os  # Document flow related
import zipfile  # zip yazo file
import shutil  # Delete the entire folder


def fromFile(url):
    try:
        with open(url, 'r', encoding='utf-8') as fp:
            return ()
    finally:
        ()
        
def fromFile2Base64(url):
    try:
        with open(url, 'rb') as f1:
            return str(base64.b64encode(()), encoding='utf-8')
    finally:
        ()

def writeInFile(toFile, content):
    try:
        with open(toFile, 'w', encoding='utf-8') as fp:
            (content)
    finally:
        ()


def fromJsonAsDict(url):
    return ((fromFile(url)))


def writeDictInFile(url, dict1):
    writeInFile(url, (dict1, ensure_ascii=False, indent=2))

def revealInFileExplorer(targetDir):
    try:
        (targetDir)
    except:
        (" %s" % targetDir)


def zipFile(src, dest):
    '''
        src: Destination file location D:/
        dest: path to the compressed output zip file D:/
    '''
    with (dest, 'w',zipfile.ZIP_DEFLATED) as p:
        
        (src,(src)[1])

        ()     


def zipFiles(src,dest):
    '''
        src: Destination folder location D:/hellowd
        dest: path to the compressed output zip D:/
    '''
    with (dest, 'w',zipfile.ZIP_DEFLATED) as pZip:
        for folder, _, files in (src):
            relative_url = (src, '')
            for file in files:
                ((folder,file),(relative_url,file))
        ()

def removeFile(url):
    if (url):
        (url)
    else:
        (url)

Simple Use Cases

# Import Translation
from Translator import Translation

zhTexts = ["I was stressed out trying to fix the merchants' concessions.","I was stressed out trying to fix the merchants' concessions.","consume{0}stamina","gain{0}a bill (e.g. 100 yuan)" ]

enTexts,enWorlds = Translation(zhTexts,'zh','en')
print(enTexts)

Python version

python 3.99

compatible version

This article on Python to achieve batch translation of the sample code is introduced to this article, more related Python batch translation content, please search for my previous posts or continue to browse the following related articles I hope that you will support me more in the future!