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

匹配模式后用for循环构建字典,提取LocalVV后续行生成对应键值对

实现方案

核心逻辑

先通过开关变量控制解析起始位置,匹配到LocalVV表头后再开始提取后续行的对应字段,生成目标字典后再做状态校验。

完整可运行代码

def parse_sync_file(file_path: str) -> dict:
    sync_dict = {}
    start_parse = False
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line_stripped = line.strip()
            # 跳过空行
            if not line_stripped:
                continue
            # 匹配到表头,开启解析,跳过当前表头行
            if 'LocalVV' in line_stripped:
                start_parse = True
                continue
            # 开启解析后处理数据行
            if start_parse:
                fields = line_stripped.split()
                # 过滤不符合格式的脏行
                if len(fields) >= 5:
                    sync_dict[fields[0]] = fields[4]
    return sync_dict

def check_sync_status(sync_dict: dict) -> bool | dict:
    abnormal_items = {k: v for k, v in sync_dict.items() if v != 'Synced'}
    return True if not abnormal_items else abnormal_items

# 调用示例,替换为你的实际文件路径
if __name__ == "__main__":
    sync_info = parse_sync_file("sample.txt")
    print("生成的字典:", sync_info)
    check_result = check_sync_status(sync_info)
    print("校验结果:", check_result)

代码说明

  • 开关变量start_parse默认关闭,只有匹配到含LocalVV的行后才会开启后续内容解析,避免前面无关行的干扰
  • 每行先做去空、空行跳过处理,兼容文件中的空行格式
  • 分割字段后先校验长度,避免格式异常的脏行导致索引报错
  • 校验逻辑直接过滤非Synced的条目,无异常返回True,有异常直接返回异常键值对

运行效果

使用你提供的样例文件运行时,生成的字典为预期格式:
{'ux_tpvv_pri.1' : 'Synced', 'ux_tpvv_pri.2' : 'Synced', 'ux_tpvv_pri.3' : 'Synced'}
校验结果返回True;如果存在状态异常的条目,会直接返回对应异常的键值对。

内容的提问来源于stack exchange,提问作者redpy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 06:39:03