Android 提取硬編碼字串 setText (python指令碼)
阿新 • • 發佈:2019-01-25
在Android 開發的過程中,我們做開發可能因為專案進度緊,沒有注意或者沒意識到硬編碼問題的重要程度會將字串直接寫進佈局檔案或者java程式碼中,這樣做是非常不符合Android開發規範的。
特別的,在產品發展到一定規模時,產品經理提出了多語言設配問題,這時候就比較難受了。
為了實現程式碼及佈局檔案中的字串提取,轉換,博主用python指令碼實現了這一步驟。
code
import os
import re
# 列出所有程式碼檔案
def list_file(dir_path=os.getcwd()):
fileList = os.listdir(dir_path)
for x in fileList:
if '.' not in x:
list_file(dir_path + '/' + x)
else:
print('-------------------------' + x)
replace(dir_path + "/" + x)
# 正則出 硬編碼的字串
def replace(path):
file = open(path, 'r', encoding='utf-8')
content = file.read()
# print('\'\'\'' + content + '\'\'\'')
pattern = re.compile(r'\.setText\(".+"\);')
bo = False
# 正則出使用setText的語句
for line in pattern.findall(content):
bo = True
print(line)
codelocation.append(line)
# 取出字串的值
value = line.split('"')[1]
# 替換java 程式碼中的硬編碼
content = content.replace('"' + value + '"', 'getString(R.string.' + value.replace(' ','_')+')')
# 儲存這個string item 到list
strList.append('<string name="' + value + '">' + value + '</string>')
# 寫入新的程式碼到
if bo:
file = open(path, 'w', encoding='utf-8')
file.write(content)
codelocation.append(path)
file.close()
rootPath = os.getcwd()
print('這個過程非常危險,建議備份資料並在家長的陪同下使用!!!')
if input('input ok to start\n') == 'ok':
# 儲存使用硬編碼的字串
strList = list()
# 儲存使用硬編碼的檔案路徑及程式碼
codelocation = list()
# 開始遍歷檔案
list_file(rootPath + '/com')
if len(strList) > 0:
stringFile = open(rootPath + '/string.xml', 'a', encoding='utf-8')
codelocationFile = open(rootPath + '/location.text', 'a', encoding='utf-8')
for x in strList:
stringFile.write(x + '\n')
print(x)
for y in codelocation:
codelocationFile.write(y + '\n')
# close file
stringFile.close()
codelocationFile.close()
小夥伴們如果安裝了python3的執行環境,可以直接複製使用哦。
how to use
- 將 上面的python程式碼複製到一個文字檔案儲存字尾名.py 將py檔案拷貝到原始碼(注意備份)的com級目錄 like this:
- 然後 按住 shift 鍵+右鍵 選擇進入命令列 輸入:
- 在命令列輸出完後,我們可以在 com同級目錄下 看到 新的兩個檔案(如果你的程式碼存在硬編碼的字串的話)。string.xml 是要你追加到android程式碼res下的string.xml字串資源,location是剛剛修改過的字串的程式碼路徑(也就是那個類被修改了)