import re import json def parse_datatype(text): datatypes = ["int16", "uint16", "int32", "uint32", "int64", "uint64"] for index, datatype in enumerate(datatypes): left, separator, right = text.partition(datatype) if len(separator) != 0: return datatype, left + right return "", text def parse_from_file(filename): data = "" with open(filename, "r", encoding='utf-8') as f: # 打开文件 linedata = "" for line in f: # 行遍历 line = line.strip() #linedata = f.readline() # 读取文件的一行 flag = bool(re.search(r'0x[0-9A-Fa-f]{4}', line)) linedata += line.strip() if flag: # print(linedata) # left, separator, right = linedata.partition("0x") parts = re.split(r'(0x[0-9A-Fa-f]{4})', linedata) linedata = "" key = parts[1] datatype, remark = parse_datatype(parts[0].strip()) remark = remark.replace("\t", " ").replace("\"", "") item = {} item["key"] = key item["datatype"] = datatype item["remark"] = remark if len(data) > 0: data += ",\n" data += ("\t\t" + json.dumps(item, ensure_ascii=False)) return data addritems = {} addritems["EMSYT"] = "EMS遥调.txt" addritems["BCUYX"] = "BCU电池簇遥信.txt" addritems["BCUYC"] = "BCU电池簇遥测.txt" addritems["BMSYC"] = "BMS电池堆遥测.txt" addritems["EMSYX"] = "EMS遥信.txt" addritems["EMSYC"] = "EMS遥测.txt" addritems["EMSYT"] = "EMS遥调.txt" addritems["PCSYX"] = "PCS遥信.txt" addritems["PCSYC"] = "PCS遥测.txt" addritems["PCUYX"] = "PCU遥信.txt" addritems["PCUYC"] = "PCU遥测.txt" addritems["MEMYC"] = "多功能电表遥测.txt" addritems["THYC"] = "温湿度状态遥测.txt" addritems["Fire40YX"] = "消防4.0遥信.txt" addritems["CoolingYX"] = "冷机遥信.txt" addritems["CoolingYC"] = "冷机遥测.txt" with open('registeraddr.json', 'w', encoding='utf-8') as f: f.write("{") count = 0 for key in addritems: filename = addritems[key] print("parse: ", key, filename) data = parse_from_file(filename) if len(data) > 0: data = "\n" + data + "\n\t" if count != 0: f.write(",") f.write("\n\t\"" + key + "\": [" + data + "]") count+=1 f.write("\n}")