You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 19:45:00