将字符串转换为字典dict
log_str = """May 20 16:25:25 10.10.77.3 date=2025-05-20,time=16: 25:25.206,device_id=FE3,log_id=02091,type=statistics,pri=information, session_id="543289-5234K89",client_name="",client_ip="10.10.66.38",client_cc="ZZ",dst_ip="10.10.77.38",from="deq@yx.com",hfrom="deq@yx.com",to="zhen@tao.com",polid="3:3:1:te.com",domain="te.com",mailer="mt",resolved="FAIL",src_type="int",direction="in",virus="",disposition="Accept",classifier="User Safe",message_length="32848",subject="客诉 1991,姓名:小二",message_id="9790d18@yx.com",recv_time="",notif_delay="0",scan_time="0.149068",xfer_time="0.018465",srcfolder="",read_status="""""
#先使用partition函数通过‘10.0.7.2’分组,获取后面字符串,然后再通过正则方式转换成字典 _, _, log_content = log_str.partition('10.0.7.2') #通过正则方式进行匹配,有的value里面会包含有逗号 pattern= r'(\w+)=(?:"((?:\\"|[^"])*)"|([^",]*))' matches = re.findall(pattern, log_content) # print(matches) logd = {} for match in matches: key = match[0] value = match[2] or match[1] # 去掉引号的内容优先 logd[key] = value print(logd)
#另外一种简单转换方法,如果遇到value中包含有逗号,会报错: _, _, log_content = log_str.partition('10.0.7.2') items = log_content.split(',') logd = {} for item in items: print(item) key, value = item.split('=', 1) logd[key.strip()] = value.strip(' "') print(logd)
浙公网安备 33010602011771号