大家都知道Android App中的字符串都保存中string.xml文件,该文件可以存放在不同目录下,不同目录下的文件用来匹配不同的语言。比如values-en目录下的文件用来匹配英语,values-zh目录下的文件就来匹配简体中文,这个目录名是专门规定的,大家可以查看官方文档。
适配不同国家的语言时需要翻译文件中的字符串,这里需要提取出string.xml文件中有用的字符串,什么是有用的字符串?我们看一下该文件中的内容:(这里只列出两行内容,省略其它行)
<string name="app_name">WeChat</string>
<string name="activity_title">Friends</string>
上面的内容中位于引号内的内容是字符串的ID,我们在程序中使用它;使用尖括号包含的内容是语法格式,我们不需要需要关注;剩下的内容用来显示到程序中,也就是用户看到的内容。我们称其为“有用的字符串”。因为我们适配其他国家的语言时就需要把这部分内容翻译成其他国家的语言。
现在我们需要把“有用的字符串从string.xml文件中提取出来,如果一行一行的提取比较麻烦,于我想到了使用phthon脚本来提取,下面是提取的步骤:
- 1.打开文件并且按行读取文件中的内容;
- 2.把每行中的内容当作一个字符串;
- 3.先去掉字符串的尾巴:,使用的是字符串的replace()方法;
- 4.提取出字符中上位于尖括号中的内容,使用了正则表达式;
- 5.替换掉步骤4中提取出的内容,使用的是字符串的replace()方法;
- 6.把剩下的尖括号替换掉,使用的是字符串的replace()方法;
- 7.把字符串写入新文件,按行写入,使用的是write()方法;
- 8.关闭文件;
接下来我们通过代码实现上的步骤,在代码中我们也添加了注释,以方便大家理解:
#! /usr/bin/python
import re
try:
# file name are two, one is for reading, other is for writing
file_in_name = "\string.xml"
file_out_name = "string_res.xml"
file_in = open(file_in_name, "r")
file_out = open(file_out_name, "w")
rule = re.compile(r'<(.*)>')
line = file_in.readline()
# read content line by line in file_in ,until the end fo file_in
while line:
# step1: remove the tail of string
result1 = line.replace("</string>", "", 1)
# step2: find the content between < >
temp = re.findall(rule, result1)
# step3: remove the content between < >
# Notice: temp is a object of list, change list to string firstly.
result2 = result1.replace(''.join(temp), "", 1)
# step4: remove the <> of string.
result3 = result2.replace("<>", "", 1)
# step5: write the result to out file
file_out.write(result3)
# read next line of in file
line = file_in.readline()
finally:
file_in.close()
file_out.close()
把上面的代码保存成python脚本文件,然后就可以从string.xml中提取文件了,提取出的内容存放在当前目录下的string_res.xml文件中。运行程序时有一点需要注意:需要把脚本和string.xml文件放到同一个目录下,或者在程序的文件名中写上string.xml的绝对路径。
下面是程序运行的结果,只列出了部分内容,达到示例作用就可以:
//运行前
<string name="app_name">WeChat</string>
<string name="activity_title">Friends</string>
//运行后
WeChat
Friends
这个是我按照自己的思路做的脚本,只为快速提取字符串。字符串的处理是个热门话题,相信大家还有其它的方法来提取字符串,欢迎大家一起交流。