Python提取文本块并将指定字段存入字典数组的方法求助
提取address-object文本块并生成字典数组
实现思路
通过空行分割文本块,筛选出以address-object开头的块,再从每个块中提取zone和host字段的值,最终组合成字典数组。
代码实现
def extract_address_objects(text): # 按空行分割文本为多个块,过滤掉空块 blocks = [block.strip() for block in text.split('\n\n') if block.strip()] result = [] for block in blocks: # 只处理address-object开头的块 if not block.startswith('address-object'): continue obj = {} lines = block.split('\n') for line in lines: line = line.strip() if line.startswith('zone'): obj['zone'] = line.split()[1] elif line.startswith('host'): obj['host'] = line.split()[1] # 确保两个字段都存在才加入结果 if 'zone' in obj and 'host' in obj: result.append(obj) return result # 测试示例 sample_text = """some other text address-object object1 name "name1" uuid 4ac9cf52-02b5-eecf-0100-18c24100da5e zone zone1 host ip1 exit address-object object2 name "name2" uuid a5c02150-a47e-748d-0100-18c24100da5e zone zone2 host ip2 exit some more text""" print(extract_address_objects(sample_text))
代码说明
- 分割文本块:使用
\n\n作为分隔符将原文本拆分为多个独立块,同时过滤掉空块,避免处理无效内容。 - 筛选目标块:检查每个块是否以
address-object开头,只处理符合条件的块。 - 提取字段值:遍历块内的每一行,识别
zone和host行,通过分割字符串获取对应的值。 - 生成结果数组:将包含完整
zone和host字段的字典加入结果数组。
运行代码后会输出:[{"host": "ip1", "zone": "zone1"}, {"host": "ip2", "zone": "zone2"}]
内容的提问来源于stack exchange,提问作者Pauwl
相关产品推荐
相关产品推荐

