iOS将项目内的国际化文本转为string格式
import os
import re
#使用前(?<!ASLocalizedString\()(?:@")([\u4E00-\u9FFF]+)(?:") 替换ASLocalizedString(@"$1")
def extract_localized_strings(folder_path):
# 所有的文件的路径
file_paths = []
# 所有的文字
localized_strings = []
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.m') or file.endswith('.swift'):
file_paths.append(os.path.join(root, file))
# 遍历所有文件
print(file_paths)
for file_path in file_paths:
with open(file_path, 'r') as f:
content = f.read()
matches = re.findall(r'ASLocalizedString\(@"([^"]*)"\)', content)
localized_strings.extend(matches)
print(len(localized_strings))
localized_strings = list(set(localized_strings))
print(len(localized_strings))
# print(localized_strings)
# 写入文件
with open('localized_strings.txt', 'w') as f:
for s in localized_strings:
f.write('"{}"="{}";\n'.format(s,s))
folder_path = input("Enter the path of the folder containing the files: ")
extract_localized_strings(folder_path)
下面是将string转excel格式,便于翻译人员翻译
import pandas as pd
import re
# 读取文本文件
with open('localized_strings.txt', 'r') as f:
data = f.read().splitlines()
# 创建正则表达式,匹配 "键"="值"; 格式的行
pattern = re.compile(r'^\"(.+)\"\=\"(.+)\"\;$')
# 提取每行的键和值,存储到列表中
data_list = []
for line in data:
match = pattern.match(line.strip())
if match:
key = match.group(1)
value = match.group(2)
data_list.append([key, value])
# 创建一个DataFrame对象
df = pd.DataFrame(data_list, columns=['key', 'value'])
# 将数据写入Excel文件
df.to_excel('output.xlsx', index=False)
再转回来
import pandas as pd
# 读取Excel文件
df = pd.read_excel('output.xlsx')
# 将数据写入文本文件
with open('output.txt', 'w') as f:
for index, row in df.iterrows():
value = str(row["value"]).replace('"', r'\"') # 将整数转换为字符串,并将引号替换为转义引号
line = f'"{row["key"]}"="{value}";\n'
f.write(line)
发表回复