常用的日志文件转json格式,自用。
import json
import re
import os
# 路径
FILE_PATH = r"C:\Users\user\Desktop\input.log"
# 匹配格式:[数字] 名称
pattern = re.compile(r"\[(\d+)\]\s*(.+)")
id_to_name = {}
name_to_id = {}
with open(FILE_PATH, "r", encoding="utf-8") as f:
for line in f:
line = line.strip()
match = pattern.search(line)
if match:
item_id = int(match.group(1))
name = match.group(2).strip()
id_to_name[item_id] = name
name_to_id.setdefault(name, []).append(item_id)
# 输出 JSON
with open("id_to_name.json", "w", encoding="utf-8") as f:
json.dump(id_to_name, f, ensure_ascii=False, indent=2)
with open("name_to_id.json", "w", encoding="utf-8") as f:
json.dump(name_to_id, f, ensure_ascii=False, indent=2)
print("解析完成!已生成 id_to_name.json 和 name_to_id.json")
print("输出目录:", os.getcwd())#同目录输出