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

相关推荐
二J1 小时前
管理100个小程序-很难吗
android·小程序
FL171713141 小时前
Mujoco & robosuite 机器人模型
xml·java·机器人
s11show_1631 小时前
hz修改后台新增keyword功能
android·java·前端
IT技术图谱2 小时前
【绝非标题党】网络监听新姿势:APT编译时注解实现高扩展框架
android·面试·架构
RichardLai883 小时前
[Flutter 基础] - Flutter基础组件 - Text
android·flutter
程序员的世界你不懂3 小时前
关于 xpath 查找 XML 元素的一点总结
xml
姜行运3 小时前
数据结构【树和二叉树】
android·数据结构·算法·c#
Dovis(誓平步青云)3 小时前
Cephalon端脑云:神经形态计算+边缘AI·重定义云端算力
图像处理·人工智能·学习·云原生·ai作画·边缘计算·机器翻译
东风西巷3 小时前
Control Center安卓版:自定义控制中心,提升手机操作体验
android·智能手机·性能优化·软件需求
布拉德很帅3 小时前
Android如何通过aspectj打造一个无侵入式动态权限申请框架
android