strings.xml匹配替換
將兩個Android專案中的多語言字串檔案(strings.xml)進行比較,如果其中一個專案中包含另一個專案沒有的字符,則合并到單一的輸出檔案,并以 key 在原始 XML 檔案中更新 value 值,如果key匹配不準確則忽略它,
具體來說:
- 引入 re, xml.etree.ElementTree 和 argparse 模塊,
- 定義命令列引數 parser,
- 決議輸入、源和輸出XML檔案,并得到其 root 節點,
- 將所有 a.xml 中的 key-value 存盤在字典 a_dict 中,
- 遍歷 b.xml 的 string 標簽,使用正則運算式判斷每個鍵是否與a_dict相等且值不同,然后更新為a_dict中的值,
- 保存修改后的b_tree到指定的輸出路徑,
- 列印成功執行修改操作的訊息,
該代碼涉及決議XML檔案、字典處理、正則運算式匹配、檔案讀寫和命令列介面設計,
import re
import xml.etree.ElementTree as ET
import argparse
parser = argparse.ArgumentParser(description='Process android strings.xml files.')
parser.add_argument('input_xml', type=argparse.FileType('r'), help='the source xml file as input')
parser.add_argument('source_xml', type=argparse.FileType('r+'), default='strings.xml', help='the xml file will be modified')
parser.add_argument('-o', '--output', type=argparse.FileType('w'), default='strings.xml', help='path to the output xml file')
args = parser.parse_args()
# 決議 a.xml 檔案
a_tree = ET.parse(args.input_xml)
a_root = a_tree.getroot()
# 決議 b.xml 檔案
b_tree = ET.parse(args.source_xml)
b_root = b_tree.getroot()
# 遍歷 a.xml 中所有 string 標簽,將其鍵值對存盤到字典 a_dict 中
a_dict = {}
for string in a_root.iter('string'):
key = string.attrib['name']
value = https://www.cnblogs.com/imorning/archive/2023/06/02/string.text
a_dict[key] = value
# 遍歷 b.xml 中所有 string 標簽,若和 a_dict 的 key 完全匹配且 value 不同,則更新為 a_dict 的 value
for string in b_root.iter('string'):
key = string.attrib['name']
if key in a_dict and string.text != a_dict[key]:
# 使用正則運算式判斷兩個 key 是否完全一致
pattern = f"^{key}$"
is_matched = bool(re.match(pattern, key))
if is_matched:
string.text = a_dict[key]
# 保存修改后的 b.xml 檔案
b_tree.write(args.output.name, encoding='utf-8', xml_declaration=True)
print(f"Successfully saved as {args.output.name}.")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/554118.html
標籤:其他
上一篇:Android strings.xml按照key修改
下一篇:返回列表