自动翻译 android/res/values/strings.xml

一、问题

自动翻译res/values/strings.xml

二、解决

本来想注册google 翻译api,不通过。(信用卡通过,身份证验证不通过,谁有办法?)

现在用百度翻译api,官网https://fanyi-api.baidu.com/product/113

如何使用通用翻译API?

  1. 使用您的百度账号登录百度翻译开放平台;
  2. 注册成为开发者,获得 APPID ;
  3. 进行开发者认证(如仅需标准版可跳过);
  4. 开通通用翻译API服务:开通链接;
  5. 参考技术文档和 Demo 编写代码。

三、例子

bash 复制代码
E:\DOWNLOADS\API_DEMO_BAIDU_TEXT_TRANSAPI_V1.0.0.0
│  test_xml_translate_main.py
│
├─out
│      strings.xml
│
└─translate_api
        Baidu_Text_transAPI.py

test_xml_translate_main.py

python 复制代码
#!/usr/bin/env python3

# zhy 20240620

'''
translate xml string
'''

import xml.etree.ElementTree as ET
import time
import sys
import translate_api.Baidu_Text_transAPI
import json

def print_string(root):
    for string in root:
        print(string.attrib)
        print(string.text)
        query = string.text
        # query = 'Hello World! This is 1st paragraph.'
        print(query)
        
        result_json_dict = translate_api.Baidu_Text_transAPI.Baidu_Text_transAPI(query)
        print(result_json_dict)
        string.text = result_json_dict['trans_result'][0]['dst']

        # with open ('test_translate_result_json.json', encoding='utf-8') as f:
        #     data = json.load(f)
        #     print(type(data))
        #     print(data)
        #     print(data['trans_result'][0]['dst'])
        #     stringaa = data['trans_result'][0]['dst']
        #     print(stringaa)
        #     # string.text = "中文内容".encode("utf-8")
        #     # string.text = "中文内容"
        #     # string.text = "aaaabbbb"
        #     string.text = stringaa


def write_out(tree):
    tree.write("out/strings_translate.xml", encoding='utf-8', xml_declaration=True)


def translate_string(file_path_strings_xml):
    tree = ET.parse(file_path_strings_xml)
    root = tree.getroot()
    print_string(root)
    write_out(tree)



def main():
    if len(sys.argv) < 2:
        print("Usage: test_xml_translate_main.py strings.xml strings.xml strings.xml ...")
        return 0

    for file_path_strings_xml in sys.argv[1:] :
        print(file_path_strings_xml)
        translate_string(file_path_strings_xml)


    return 0




if __name__ == "__main__":
    sys.exit(main())

Baidu_Text_transAPI.py

python 复制代码
# -*- coding: utf-8 -*-

# This code shows an example of text translation from English to Simplified-Chinese.
# This code runs on Python 2.7.x and Python 3.x.
# You may install `requests` to run this code: pip install requests
# Please refer to `https://api.fanyi.baidu.com/doc/21` for complete api document

import requests
import random
import json
from hashlib import md5
import time

# Set your own appid/appkey.

appid = 'INPUT_YOUR_APPID'
appkey = 'INPUT_YOUR_APPKEY'



# For list of language codes, please refer to `https://api.fanyi.baidu.com/doc/21`
from_lang = 'en'
to_lang =  'zh'

endpoint = 'http://api.fanyi.baidu.com'
path = '/api/trans/vip/translate'
url = endpoint + path

query = 'Hello World! This is 1st paragraph.\nThis is 2nd paragraph.'

# Generate salt and sign
def make_md5(s, encoding='utf-8'):
    return md5(s.encode(encoding)).hexdigest()



def Baidu_Text_transAPI(query):
    # 免费版 Qps=1
    time.sleep(1)
    
    # Generate salt and sign
    salt = random.randint(32768, 65536)
    sign = make_md5(appid + query + str(salt) + appkey)

    # Build request
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    payload = {'appid': appid, 'q': query, 'from': from_lang, 'to': to_lang, 'salt': salt, 'sign': sign}

    # Send request
    r = requests.post(url, params=payload, headers=headers)
    result_json_dict = r.json()

    # Show response
    result_json_str= json.dumps(result_json_dict, indent=4, ensure_ascii=False)
    print(result_json_str)
    return result_json_dict

strings.xml

xml 复制代码
<?xml version='1.0' encoding='utf-8'?>
<resources>
    <string name="hello_world">Hello World!</string>
    <string name="hello_china">Hello China!</string>
    <string name="hello_python">Hello Python!</string>

</resources>
bash 复制代码
申请百度翻译账号,填写
appid = 'INPUT_YOUR_APPID'
appkey = 'INPUT_YOUR_APPKEY'

python.exe .\test_xml_translate_main.py .\out\strings.xml

生成 .\out\strings_translate.xml
英语字符,被翻译成中文字符

例子简单粗糙,记录一下,备忘。

四、参考

为什么要使用谷歌云的翻译接口

http://www.tadke.com/wangzhan-jiaocheng/wordpress-jiqiao/02/26552.html

百度翻译开发平台

https://fanyi-api.baidu.com/product/113

Python数据处理(一):处理 JSON、XML、CSV 三种格式数据

https://juejin.cn/post/7047386538266755103

菜鸟教程 Python3 XML 解析

https://www.runoob.com/python3/python3-xml-processing.html

相关推荐
Android-Flutter9 分钟前
kotlin - 显示HDR图(heic格式),使用GainMap算法,速度从5秒提升到0.6秒
android·kotlin
雨白1 小时前
协程进阶:协作、互斥与共享状态管理
android·kotlin
用户41659673693551 小时前
深度剖析 Android Context:启动 Activity 与 View 创建的“内幕”
android
方白羽1 小时前
Android 唯一UUID方案
android·app
一个小狼娃1 小时前
Android集成Unity避坑指南
android·游戏·unity
川石课堂软件测试2 小时前
Python | 高阶函数基本应用及Decorator装饰器
android·开发语言·数据库·python·功能测试·mysql·单元测试
行走的陀螺仪2 小时前
Flutter 开发环境配置教程
android·前端·flutter·ios
萝卜白菜。2 小时前
关于Java EE应用中xml解析类的问题
xml·java·java-ee
前端与小赵3 小时前
uni-app开发安卓app时控制屏幕常亮不息屏
android·gitee·uni-app
百锦再3 小时前
第8章 模块系统
android·java·开发语言·python·ai·rust·go