自动翻译 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

相关推荐
闲暇部落1 小时前
‌Kotlin中的?.和!!主要区别
android·开发语言·kotlin
诸神黄昏EX3 小时前
Android 分区相关介绍
android
大白要努力!4 小时前
android 使用SQLiteOpenHelper 如何优化数据库的性能
android·数据库·oracle
Estar.Lee4 小时前
时间操作[取当前北京时间]免费API接口教程
android·网络·后端·网络协议·tcp/ip
Winston Wood4 小时前
Perfetto学习大全
android·性能优化·perfetto
Dnelic-7 小时前
【单元测试】【Android】JUnit 4 和 JUnit 5 的差异记录
android·junit·单元测试·android studio·自学笔记
Eastsea.Chen10 小时前
MTK Android12 user版本MtkLogger
android·framework
长亭外的少年17 小时前
Kotlin 编译失败问题及解决方案:从守护进程到 Gradle 配置
android·开发语言·kotlin
建群新人小猿19 小时前
会员等级经验问题
android·开发语言·前端·javascript·php
1024小神21 小时前
tauri2.0版本开发苹果ios和安卓android应用,环境搭建和最后编译为apk
android·ios·tauri