it编程 > 前端脚本 > Python

Python解析Android项目中的strings.xml

7人参与 2025-07-25 Python

python 解析 android 项目里的 strings.xml

针对大家在 android 项目中可能用到的多国语言翻译,需要把 value 里的内容解析出来,方便做编辑,可以使用以下 python 脚本轻松实现

import xml.etree.elementtree as et

# 解析 strings.xml 文件
xml_file = 'strings.xml'
tree = et.parse(xml_file)
root = tree.getroot()

# 提取所有 <string> 标签的 name 和内容
strings_dict = {}
for string_elem in root.findall('string'):
    name = string_elem.get('name')
    value = string_elem.text
    strings_dict[name] = value

# 输出结果
for k, v in strings_dict.items():
    print(f'{k}: {v}')
    # print(f'{v}')

python将android strings.xml导出到excel

做android开发的时候要做国际化,需要将android工程中的字符串资源导出到excel,让专业团队翻译。由于项目比较多,手动复制不现实,故使用python 将xml文件中对应的字符串解析到excel中。

用法

复制以下代码到python文件中,如string2excel.py, 添加可执行权限(mac 电脑 chmod +x string2excel.py),将所有要导出的strings.xml复制到string2excel.py同一目录下,执行./string2excel.py 就会在同级目录下生成excel文件。

#!/usr/bin/env python
# -*- coding:utf-8 -*-

#android国际化: 将xml文件中对应的字符串解析到excel中

import xml.dom.minidom
from xlwt import workbook
import os
def all_path(dirname,subfix):

    result = []#所有的文件
    filter=[subfix] #设置过滤后的文件类型 当然可以设置多个类型

    for maindir, subdir, file_name_list in os.walk(dirname):

        # print("1:",maindir) #当前主目录
        # print("2:",subdir) #当前主目录下的所有目录
        # print("3:",file_name_list)  #当前主目录下的所有文件

        for filename in file_name_list:
            apath = os.path.join(maindir, filename)#合并成一个完整路径
            ext = os.path.splitext(apath)[1]  # 获取文件后缀 [0]获取的是除了文件名以外的内容
            if ext in filter:
               result.append(apath)

    return result

#新建一个workbook
book = workbook(encoding='utf-8')
#生成的excel表名称
excel_file_name = 'android_strings.xls'
#要处理的文件所在路径及文件后缀
all_file=all_path("./",".xml")

#打印所有要输出的文件的路径及名称
print(all_file)

sheet_info = []

class sheetinfo:
    sheet_name=''
    elementcount = 0
    def __init__(self, name, count):
        self.sheet_name = name
        self.elementcount = count


for file in all_file:

    filename= os.path.splitext(os.path.basename(file))[0]

    sheet = book.add_sheet(filename)

    #打开xml
    xmldoc = xml.dom.minidom.parse(file)
    code = xmldoc.getelementsbytagname('string')

    #表头
    row = 0
    sheet.write(row, 0, 'key')
    sheet.write(row, 1, 'en')
    row = row+1

    #读取每一行写到excel中
    for node in code:
        for item in node.childnodes:
            sheet.write(row, 0, node.getattribute('name'))
            sheet.write(row, 1, item.data)

        row = row+1

    #记录表名和行数,用于统计
    sheet_info.append(sheetinfo(filename,row-1))
#保存workbook
book.save(excel_file_name)

#增加汇总表
sheet = book.add_sheet('汇总')
row= 1
for element in sheet_info:
    sheet.write(row, 0, element.sheet_name)
    sheet.write(row, 1, element.elementcount)
    row = row+1
#保存workbook
book.save(excel_file_name)

python实现android国际化多语言strings.xml文件与excel互转

下面将通过python脚本实现strings.xml文件中的多语言文本转换到excel表格,同时提供了两种转换功能:strings.xml转excel和excel转strings.xml

完整代码

#可实现string.xml中资源汇总到excel文件,需自行创建in文件夹,并把string.xml文件全部放入,生成excel在out文件夹
#也可通过excel统计的资源生成对应string.xml,放至out文件夹

import openpyxl  
import os  
import xml.etree.elementtree as et

outpath="out"
outexcelname=os.path.join(outpath, '翻译文本.xlsx')
inpath="in"

def check_suffix(filepath):
    return os.path.splitext(filepath)[1]=='.xml'
    
def check_out_put():
    # 检查文件夹是否存在  
    if not os.path.exists(outpath):  
        # 如果文件夹不存在,则创建文件夹  
        os.makedirs(outpath)

def excel_2_xml():  
    path = input("请输入excel文件(.xlsx)路径: ")
    # path = "d:/code/py_stringxml/tets.xlsx"
    
    # 打开excel文件  
    workbook = openpyxl.load_workbook(path)  
  
    # 获取工作表对象  
    worksheet = workbook.active  
    # 检查/创建输出路径  
    check_out_put()
    
    # 遍历列数据,不包含最大数  
    for col in range(2, worksheet.max_column+1):
        # 取excel当前列第一行作为strings.xml的文件名
        filename = os.path.join(outpath, worksheet.cell(row=1, column=col).value)
        print("file name:", filename) 
        
        # 创建根元素
        root = et.element("resources")  
        
        for rows in range(2, worksheet.max_row+1):
            #每一行第一列为name
            key = worksheet.cell(rows, 1).value
            value = worksheet.cell(rows, col).value
  
            # 创建子元素  
            if not value is none:
                item = et.subelement(root, "string", name=key)  
                item.text = value  
        
        # 将xml写入文件  
        tree = et.elementtree(root)  
        # 添加换行和缩进
        et.indent(tree, space='\t', level=0)
        tree.write(filename, xml_declaration=true, encoding="utf-8")
        
    # 关闭excel文件  
    workbook.close()
    
    print("处理完成")
  
def xml_2_excel():  
    # 检查/创建输出路径  
    check_out_put()
    # 删除上次生成的excel文件
    if os.path.isfile(outexcelname):
        os.remove(outexcelname)
    
    # 创建一个新的工作簿对象  
    workbook = openpyxl.workbook()  
    # 选择活动工作表  
    worksheet = workbook.active 
    
    stringnames=[]
    # 第一列存放string.xml中的name,翻译文件从第二列开始
    col=2
    # 遍历输入路径夹中所有xml文件
    for file in os.listdir(inpath):
        # 非xml后缀名不做处理
        if check_suffix(file) is false:
            continue
        print("file", file)
        
        row=1
        # 解析 xml 文件  
        tree = et.parse(os.path.join(inpath, file))  
        # 获取根元素  
        root = tree.getroot()
        
        #设置单元格属性(自动换行,顶端对齐)
        cell_style = openpyxl.styles.alignment(vertical='top', wrap_text=true)   
        #excel文件名添加到第一行
        worksheet.cell(row=row, column=col, value=file)
        # 从第二行开始写入value值
        row=row+1
        # 遍历所有子元素  
        for child in root.iter():  
            key = child.get('name')
            if key is none:
                continue
            # 判断元素是否已经添加到excel文件,将xml的name添加到第一列
            if key in stringnames:
                # 找出当前元素所在行
                # 数组下标从零开始,excel文件下标从1开始,得加1,第一行是文件名,再加1
                row = stringnames.index(key)+2
                
            else:
                # 元素名添加到数组
                stringnames.append(key)
                # 添加到最后一行,第一行是文件名,得加1
                row = len(stringnames)+1
                m_cell = worksheet.cell(row=row, column=1) 
                m_cell.value = key  
                # 设置单元格属性
                m_cell.alignment = cell_style    
            
            value = child.text
            
            # 将翻译的文本内容写入对应excel单元格  
            if not key is none:
                # print("current", col, row)
                m_cell = worksheet.cell(row=row, column=col) 
                m_cell.value = value  
                # 设置单元格属性
                m_cell.alignment = cell_style
            else:
                print("key is none:", col, row)
            # 写入下一行
            row=row+1
        # 下一个文件从下一列开始
        col=col+1
    
    for i in range(1, col):  
        #因为列名是字母需要将数字转换成字母
        c = openpyxl.utils.get_column_letter(i) 
        #设置单元格宽度
        worksheet.column_dimensions[c].width = 40 
    
    # 保存excel文件        
    workbook.save(outexcelname)
    
    print("处理完成")
        
if __name__ == "__main__":  
    select = input("请输入操作选项:\n1、excel文件转换成string.xml\n2、string.xml转换成excel文件\n")
    if select == "1":
        excel_2_xml()  
    else:
        xml_2_excel()
    input("按任意键退出...")

到此这篇关于python解析android项目中的strings.xml的文章就介绍到这了,更多相关python解析android中xml内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

您想发表意见!!点此发布评论

推荐阅读

Python利用ElementTree库处理XML的完全指南

07-25

Python实现PDF转Markdown的完整方案与代码

07-25

基于Python实现本地文件内容搜索工具

07-25

Python实现将CSV转换为带格式的Excel

07-25

利用Python开发一个简单的密码管理器

07-25

Python实现修改PDF文件内部属性值

07-25

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论