# coding=gbk
import os
import re
#字典 key--变量名, value--变量地址
dictVariable={}
#读取map文件,找到变量名和变量地址,并放入字典
def readMap():
print("readMap!!! ")
flagFindPrefix = 0
with open("test_demo.map", "r") as f: #逐行读取文件
cows = f.readlines()
for cow in cows:
m = re.match('\s{2}_\w+', cow) #找到变量名对应的行
if m:
key = m.group()[3:] #提取变量名
# print(key)
flagFindPrefix = 1
n = re.match('\s+(\w+)\s+\w+\s+data\s,g\s+\w+', cow) #提取变量地址对应的行
if n and flagFindPrefix == 1:
flagFindPrefix = 0
b = n.group()
if b:
# print(b[34:42])
dictVariable[key] = b[34:42] #提取变量地址,并放入字典
# print(dictVariable)
#读取a2l文件,替换变量地址
def replaceA2l():
print("replaceA2l!!! ")
with open("SCM_ASW.a2l", "r") as f:
cows = f.readlines() #逐行读取文件
with open('Res_SCM_ASW.a2l', 'w') as f: #打开要写入的新文件
for cow in cows:
n = re.search(r'@ECU_Address@\w+@', cow) #找到要替换的行
if n:
key = n.group()[13:-1] #提取要替换的行的变量名
# print(key)
# print(dictVariable[key])
cow = cow.replace('0000', dictVariable[key]) #替换地址0为,变量对应的地址
f.write(cow) #逐行写入文件
#主函数
def main():
readMap()
replaceA2l()
print("replace end!!! ")
os.system('pause')
if __name__ == '__main__':
main()