Python如何从文本文件提取hostname与datetime并关联存储为字典
Python提取字段并存字典实现方案
直接通过正则匹配提取目标字段后配对即可,完整可运行代码如下:
import re # 从本地文件读取内容请取消注释下方两行,并替换为你的文件路径 # with open('target_file.txt', 'r', encoding='utf-8') as f: # text = f.read() # 此处为示例文本,实际使用时可替换为文件读取的内容 text = """- Stdout: | notAfter=Jun 2 10:15:03 2031 GMT UnitId: octavia/1 - Stdout: | notAfter=Jun 2 10:15:03 2031 GMT UnitId: octavia/0 - Stdout: | notAfter=Jun 2 10:15:03 2031 GMT UnitId: octavia/2""" # 定义正则匹配规则 re_not_after = re.compile(r'notAfter=([\w\s:,]+)') re_unit_id = re.compile(r'UnitId: (\S+)') # 提取所有匹配的日期和hostname datetime_list = [dt.strip() for dt in re_not_after.findall(text)] hostname_list = re_unit_id.findall(text) # 配对存入字典,key为hostname,value为对应日期 result = dict(zip(hostname_list, datetime_list)) # 输出验证结果 print(result)
运行后输出结果如下:
{'octavia/1': 'Jun 2 10:15:03 2031 GMT', 'octavia/0': 'Jun 2 10:15:03 2031 GMT', 'octavia/2': 'Jun 2 10:15:03 2031 GMT'}
如果需要将日期字符串转换为Python datetime对象,可以新增以下处理逻辑:
from datetime import datetime formatted_result = {} for hostname, dt_str in result.items(): # 按日期格式转换为datetime对象 dt_obj = datetime.strptime(dt_str, '%b %d %H:%M:%S %Y GMT') formatted_result[hostname] = dt_obj
内容的提问来源于stack exchange,提问作者sunbey
相关产品推荐
相关产品推荐

