This commit is contained in:
huxiaoshuang
2022-11-23 10:27:46 +08:00
parent e53b074e11
commit 2f1aa67896
4 changed files with 380 additions and 0 deletions

50
BaiduTrans.py Normal file
View File

@@ -0,0 +1,50 @@
# 百度通用翻译API,不包含词典、tts语音合成等资源如有相关需求请联系translate_api@baidu.com
# coding=utf-8
import http.client
import hashlib
import urllib
import random
import json
import time
appid = '20181013000218671' # 填写你的appid
secretKey = '3CJvgUQRitUNeo7shcTJ' # 填写你的密钥
httpClient = None
myurl = '/api/trans/vip/translate'
# fromLang = 'auto' # 原文语种
# toLang = 'zh' # 译文语种
# toLang = 'en' # 译文语种
salt = random.randint(32768, 65536)
q = 'apple'
def transBaidu(q='hello',fromLang='',toLang=''):
# print('q---',q)
sign = appid + q + str(salt) + secretKey
sign = hashlib.md5(sign.encode()).hexdigest()
global myurl
myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign
try:
httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
httpClient.request('GET', myurl)
# response是HTTPResponse对象
response = httpClient.getresponse()
result_all = response.read().decode("utf-8")
result = json.loads(result_all)
# print (type(result))
# print ((result))
# print('翻译结果-----',result['trans_result'][0]["dst"])
time.sleep(1) #限制频率
# print(result)
return(result['trans_result'][0]["dst"])
except Exception as e:
print('error---',e)
finally:
if httpClient:
httpClient.close()

163
app.py Normal file
View File

@@ -0,0 +1,163 @@
# from importlib.resources import path
import os
import re
import string
import time
from BaiduTrans import transBaidu
from trans import getinfo,postData,transI18,transWord
from tclient import tenTrans
import requests
import random
# 处理单个文件
def transFile(fileName):
# 生成新的数据data [lines的形式]
newData=[]
print('执行文件===>',fileName)
# 读取每一行
with open(fileName,'r',encoding='utf8') as fLines:
# for line in fLines.readlines(): #依次读取每行
for index,line in enumerate(fLines.readlines()): #依次读取每行
newline = line.strip() #去掉每行头尾空白 -获取字符串
# print ("读取的数据为: %s" % (line))
# .* 表示任意匹配除换行符(\n、\r之外的任何单个或多个字符
# (.*?) 表示"非贪婪"模式,===>只保存第一个匹配到的子串
# ^title: |^label: | :使用模板字符串 =使用{}
matchObj = re.match( r'(.*text: |.*title: |.*label: |.*label=|.*placeholder=|.*message: |.*placeholder: |.*title=)["||\'](.*?)["||\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
matchObjsingal = re.match( r'(.*text: |.*title: |.*label: |.*message: |.*placeholder: )[\'](.*?)[\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
matchObjmore = re.match( r'(.*text: |.*title: |.*label: |.*message: |.*placeholder: )["](.*?)["]', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
matchquerysl= re.match( r'(.*label=|.*placeholder=|.*title=)[\'](.*?)[\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
matchquerymore= re.match( r'(.*label=|.*placeholder=|.*title=)["](.*?)["]', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
# 识别中文字符
znRe=re.match( r'.*["||\']([\u4e00-\u9fa5]+?)["||\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
znResigal=re.match( r'.*["||\']([\u4e00-\u9fa5]+?)["||\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
znRemore=re.match( r'.*["||\']([\u4e00-\u9fa5]+?)["||\']', newline, re.M|re.I) #匹配title/label开始---- '/"结束 | re.M|
# 匹配
if matchObj:
# if False:
print ("原始语句------------------------ : ", matchObj.group()) #label: "hello'
# print ("matchObj.group(1) : ", matchObj.group(1)) #标识符 label:
# print ("matchObj.group(2) : ", matchObj.group(2)) #要替换的字符串 hello
oldWord=matchObj.group(2)
# enWord=transBaidu(oldWord,'zh','en') # 百度-执行中文翻译
enWord=tenTrans(oldWord,'zh','en') # 执行中文翻译
Idword=tenTrans(oldWord,'zh','id') # 执行印尼翻译 --api不支持
key=transI18(oldWord,enWord,Idword)
globalKey='`${'+'window.i18n("{key}")'.format(key=key)+'}`'
reline=line
if matchObjsingal:
reline=line.replace("'{}'".format(oldWord),globalKey,1) #仅全局替换1次字符
elif matchObjmore:
reline=line.replace("\"{}\"".format(oldWord),globalKey,1) #仅全局替换1次字符
elif matchquerysl:
if '==' not in line or '?' not in line:
globalKey='{'+'`${'+'window.i18n("{key}")'.format(key=key)+'}`'+'}'
reline=line.replace("'{}'".format(oldWord),globalKey,1) #仅全局替换1次字符
elif matchquerymore:
# 判断?或者==表达式 [排除翻译]
if '==' not in line or '?' not in line:
globalKey='{'+'`${'+'window.i18n("{key}")'.format(key=key)+'}`'+'}'
reline=line.replace("\"{}\"".format(oldWord),globalKey,1) #仅全局替换1次字符
#replace替换-字符串
# reline=line.replace("'{}'".format(oldWord),globalKey,1) #仅全局替换1次字符
print('globalKey--',globalKey)
print('替换语句------------------------ ',reline)
#每行写入
newData.append(reline)
else:
# 识别中文字符
newznList=re.findall("[\u4e00-\u9fa5]+",newline)
newznListsignal=re.findall('[\u4e00-\u9fa5]+',newline)
# newznListMore=re.findall('[\u4e00-\u9fa5]+',newline)
# newznList=re.findall('["||\'][\u4e00-\u9fa5]+["||\']',newline)
# newznListsignal=re.findall('[\'][\u4e00-\u9fa5]+[\']',newline)
# newznListMore=re.findall('["][\u4e00-\u9fa5]+["]',newline)
print('newznList',newznList)
print('newznListsignal',newznListsignal)
# print('newznListMore',newznListMore)
# 没有中文字符
if(len(newznList)==0):
# print ("No match!!")
newData.append(line)
else:
znline=line
# znline=tensWord(line,newznList)
for index,znWord in enumerate(newznList):
# print('newList',newznList)
# 翻译中文单词-英文
# enWord=transBaidu(znWord,'zh','en') # 百度-执行中文翻译
enWord=tenTrans(znWord,'zh','en') # 执行中文翻译
Idword=tenTrans(znWord,'zh','id') # 执行印尼翻译 --api不支持
enwordkey=transI18(znWord,enWord,Idword)
print('znWord---enWord',znWord,enWord)
enwordKey='`${'+'window.i18n("{key}")'.format(key=enwordkey)+'}`'
# znline=znline.replace(znWord,enwordKey,1) #仅全局替换1次字符
if znWord in newznListsignal:
print('单个')
znline=znline.replace("'{}'".format(znWord),enwordKey,1) #仅全局替换1次字符
znline=znline.replace("\"{}\"".format(znWord),enwordKey,1) #仅全局替换1次字符
# znline=znline.replace(znWord,enwordKey,1) #仅全局替换1次字符
print('znline1--',znline)
# if znWord in newznListMore:
# print('双引号')
# print('znline222--',znline)
# znline=znline.replace("\"{}\"".format(znWord),enwordKey,1) #仅全局替换1次字符
# # znline=znline.replace(znWord,enwordKey,1) #仅全局替换1次字符
# print('znline2--',znline)
# znline=znline.replace("\"{}\"".format(znWord),enwordKey,1) #仅全局替换1次字符
# print('znline--',znline)
print('znline--',znline)
newData.append(znline)
# 写入文件
with open(fileName,'w',encoding='utf8') as newfLines:
newfLines.writelines(newData)
def listFile():
newDir = input('请输入文件或者目录:')
# 判断类型: 文件还是目录
#1. 文件类型
if(os.path.isfile(newDir)):
transFile(newDir)
# pass
else:
#2. 目录类型
print('遍历目录',newDir)
for root, dirs, files in os.walk(eval(repr(newDir.replace('"', '')))):
# for root, dirs, files in os.walk(eval(repr(".")) , topdown=False):
# 遍历子目录
for name in dirs:
pass
# 遍历文件名
for name in files:
fileName=os.path.join(os.getcwd(), root,name) #windows系统异常
print(fileName)
transFile(fileName)
# 主程序-打包exe
if __name__=='__main__':
listFile()
input("按任意键回车停止")
print("已停止")

51
tclient.py Normal file
View File

@@ -0,0 +1,51 @@
import json
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
from tencentcloud.tmt.v20180321 import tmt_client, models
def tenTrans(SourceText='',Source='zh',Target=''):
try:
# 实例化一个认证对象入参需要传入腾讯云账户secretIdsecretKey,此处还需注意密钥对的保密
# 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
cred = credential.Credential("AKIDZ1CFLH3dz8HJ7jicO2TVRAgFua7RXQ6m", "rVza2GMMExW2k5JSaZJyY3QrBLRJyQfu")
# 实例化一个http选项可选的没有特殊需求可以跳过
httpProfile = HttpProfile()
httpProfile.endpoint = "tmt.tencentcloudapi.com"
# 实例化一个client选项可选的没有特殊需求可以跳过
clientProfile = ClientProfile()
clientProfile.httpProfile = httpProfile
# 实例化要请求产品的client对象,clientProfile是可选的
client = tmt_client.TmtClient(cred, "ap-beijing", clientProfile)
# 实例化一个请求对象,每个接口都会对应一个request对象
req = models.TextTranslateRequest()
params = {
"SourceText": SourceText,
"Source": Source,
"Target": Target,
"ProjectId": 1314553376
}
req.from_json_string(json.dumps(params))
# 返回的resp是一个TextTranslateResponse的实例与请求对象对应
resp = client.TextTranslate(req)
# 输出json格式的字符串回包
print(resp.to_json_string())
print(resp.TargetText)
return(resp.TargetText)
# {
# "Response": {
# "RequestId": "6c9f968b-4149-4256-a567-8af75f28e180",
# "Source": "zh",
# "Target": "en",
# "TargetText": "Hello"
# }
# }
except TencentCloudSDKException as err:
print(err)

116
trans.py Normal file
View File

@@ -0,0 +1,116 @@
from BaiduTrans import transBaidu
import requests
import random
import os
import re
import time
from tclient import tenTrans
def getinfo(oldWord):
print('查询多语言------------------------ ')
searchUrl='http://vision.xytech.com/api/language/index'
searchPayload = {'bizId': '48', 'current': '1','pageSize': '10','search':oldWord}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36','Accept':'application/json, text/plain, */*','Content-Type':'application/json; charset=utf-8','Cookie':'_clck=1becfu3|1|f11|0; locale=zh_CN; XY_USER=t0LuUri548F8CcdkpOeuJw==s'}
r = requests.get(searchUrl,headers=headers, params=searchPayload)
return r
def postData(oldWord='',newWord='',Idword='',newkey=''):
print('!!!!!!===新增多语言====!!!!!!!! ')
print('中文:',oldWord)
print('英文:',newWord)
# print('印尼:',Idword)
print('key编码:',newkey)
print('-------------------------------')
postUrl='http://vision.xytech.com/api/language/create'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36','Accept':'application/json, text/plain, */*','Content-Type':'application/json; charset=utf-8','Cookie':'_clck=1becfu3|1|f11|0; locale=zh_CN; XY_USER=t0LuUri548F8CcdkpOeuJw==s'}
# in_ID印尼语=>'in_ID':Idword,
postPayload={'bizId':'48','en_US':newWord,'key':newkey,'zh_CN':oldWord,'in_ID':Idword,'id':45809}
r = requests.post(postUrl,headers=headers, params=postPayload)
return r
def transI18(oldWord:str,newWord:str,Idword:str):
# print('调用多语言接口------------------------ ')
# 生成自由编码
newkey=''
try:
# newkey=newWord.replace(' ','-') +'-'+str(random.randint(1,10000) )
newkey=newWord.replace(' ','_') +'_'+str(random.randint(1,10000) ) # 下划线容易复制
except:
newkey=oldWord+'-'+str(random.randint(1,10000))
print('生成key: ',newkey)
r = getinfo(oldWord)
newlist=r.json()["data"]
if(len(newlist)>0):
itemArr=[]
for item in newlist:
itemArr.append(item["key"])
itemArr.append(item["zh_CN"])
if item["zh_CN"]==oldWord:
print('中文数据存在------------------------ ')
newkey=item["key"]
print('newkey-----',newkey)
break
elif item["key"]==oldWord:
# pass
print('key数据存在------------------------ ')
newkey=item["key"]
break
else:
pass
# print('数据库不存在------------------------ ')
#post新增接口
if newWord!='None' :
r =postData(oldWord,newWord,newkey)
print('post----',r.json())
if oldWord not in itemArr:
print('数据库不存在------------------------ ')
#post新增接口
# r =postData(oldWord,newWord,Idword,newkey)
else:
# print('没有查询结果')
#post新增接口
newWord!='None' :
r =postData(oldWord,newWord,Idword,newkey)
# print('即将替换的key值------------------------ ',newkey)
return newkey
# oldWord=input('请输入要翻译的单词:')
# newWord=transBaidu(oldWord) # 执行翻译
# key=transI18(oldWord,newWord)
# globalKey='`${'+'window.i18n("{key}")'.format(key=key)+'}`'
def transWord():
print('windows请先关闭charles和clash代理')
oldWord=input('请输入要翻译的单词:')
newWord=transBaidu(oldWord,'zh','en') # 百度-执行中文翻译
newWord=tenTrans(oldWord,'zh','en') # 执行中文翻译
Idword=tenTrans(oldWord,'zh','id') # 执行印尼翻译 --api不支持
key=transI18(oldWord,newWord,Idword)
win='window.i18n("{key}")'.format(key=key)
globalKey='`${'+'window.i18n("{key}")'.format(key=key)+'}`'+', //'+'{oldWord}'.format(oldWord=oldWord)
objStr='{`'+'window.i18n("{key}")'.format(key=key)+'`}'
print('-----------------')
print("中文: ",oldWord)
print("英语: ",newWord)
print("印尼: ",Idword)
print('-----------------')
print("key:",key)
print("win语句:",win)
print("str语句:",globalKey)
print("obj语句:",objStr)
print('-----------------')
print(' ')
# 主程序-打包exe
if __name__=='__main__':
while True:
transWord()