当前位置: 首页 > article >正文

百度翻译API翻译Qt LinguistTools的ts文件

# coding=utf-8

import http.client
import hashlib
import urllib
import random
import json
import xml.etree.ElementTree as ET
import time

appid = ''  # 填写你的appid
secretKey = ''  # 填写你的密钥


def translate_text(text):
    httpClient = None
    myurl = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
    result = ''

    fromLang = 'zh'  # 原文语种
    toLang = 'en'  # 译文语种
    salt = random.randint(32768, 65536)
    #text = '苹果'
    sign = appid + text + str(salt) + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(
        text) + '&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(result)
        result = result['trans_result'][0]['dst']
        return result;

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()


def translate_ts_file(input_file, output_file):
    # 解析 TS 文件
    tree = ET.parse(input_file)
    root = tree.getroot()

    # 遍历所有的消息
    for context in root.findall('context'):
        for message in context.findall('message'):
            source = message.find('source')
            if source is not None:
                text_to_translate = source.text
                if text_to_translate:
                    print(f'Translating: {text_to_translate}')
                    translated_text = translate_text(text_to_translate)

                    translation = message.find('translation')
                    if translation is None:
                        translation = ET.SubElement(message, 'translation', type="unfinished")
                    else:
                        translation.set('type', 'finished')  # 更新 type 属性
                    translation.text = translated_text
                    time.sleep(1);


    # 写入翻译后的 TS 文件
    tree.write(output_file, encoding='utf-8', xml_declaration=True)
    print(f'Translated TS file saved as: {output_file}')

if __name__ == "__main__":
    filename = input("请输入ts文件名(en):")
    translate_ts_file(filename, filename)

由于API限制访问频率,所以加了sleep


推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/3Zqhgt


http://www.kler.cn/news/290679.html

相关文章:

  • 百度飞浆目标检测PPYOLOE模型在PC端、Jetson上的部署(python)
  • React 创建和嵌套组件
  • 策略规划:在MySQL中实现数据恢复的全面指南
  • [Python图论]在用图nx.shortest_path求解最短路径时,节点之间有多条边edge,会如何处理?
  • 【MySQL】索引使用规则——(覆盖索引,单列索引,联合索引,前缀索引,SQL提示,数据分布影响,查询失效情况)
  • Proteus 仿真设计:开启电子工程创新之门
  • Unity3D中控制3D场景中游戏对象显示层级的详解
  • 构建数据恢复的硬件基础:MySQL中的硬件要求详解
  • draw.io图片保存路径如何设置
  • linux(ubuntu)安装QT-ros插件
  • Ferrari求解四次方程
  • VTK随笔十三:QT与VTK的交互
  • jupyter 笔记本中如何判定bash块是否执行完毕
  • CentOS7 yum 报错解决方案
  • FFmpeg源码:get_audio_frame_duration、av_get_audio_frame_duration2函数分析
  • Splasthop 安全远程访问帮助企业对抗 Cobalt Strike 载荷网络攻击
  • 鸿蒙(API 12 Beta6版)图形【NativeImage开发指导 (C/C++)】方舟2D图形服务
  • git---gitignore--忽略文件
  • 【C++】对比讲解构造函数和析构函数
  • 智能优化特征选择|基于鲸鱼WOA优化算法实现的特征选择研究Matlab程序(KNN分类器)
  • idea对项目中的文件操作没有权限
  • 海外合规|新加坡网络安全认证计划简介(三)-Cyber Trust
  • SpringBoot+Redis极简整合
  • springboot集成七牛云上传文件
  • Python画笔案例-030 实现打点之斜正方
  • MATLAB 中的对数计算
  • torch、torchvision、torchtext版本兼容问题
  • ubuntu 22.04安装NVIDIA驱动和CUDA
  • 传统CV算法——基于 SIFT 特征点检测与匹配实现全景图像拼接
  • Java实现根据某个字段对集合进行去重并手动选择被保留的对象