如何遍历多个不同的文本/conf文件匹配关联信息并生成整合后的输出文件?
解决方案:关联多文件URI数据并生成统一格式输出
嘿,我完全懂你的困扰——四个分散的文件要按URI精准关联,还得处理部分URI缺失的情况,按行硬匹配肯定行不通。咱们用Python来搞定这个,思路清晰又好调整:先把后面三个文件的内容存成以URI为键的字典,然后遍历第一个文件的每个前端URI,去字典里查对应信息,最后拼接成你要的格式就行。
具体实现步骤与代码
- 把协议标识、主机地址、后端URI三个文件的数据加载成字典,URI作为键,对应的值作为字典值,这样查询效率超高;
- 遍历第一个文件的每个前端URI,从三个字典中提取对应数据,缺失的字段用
N/A标记; - 将拼接好的每行内容写入新的输出文件。
直接上可运行的代码,你只需根据实际文件名修改路径即可:
# 替换成你自己的文件路径 frontend_file = "frontend_uris.txt" proto_file = "proto_flags.txt" host_file = "hosts.txt" backend_file = "backend_uris.txt" output_file = "final_result.txt" # 初始化三个字典存储关联数据 proto_map = {} host_map = {} backend_map = {} # 读取协议标识文件,构建URI->标识的映射 with open(proto_file, 'r') as f: for line in f: line = line.strip() if not line: continue # 按第一个空格分割URI和标识(假设URI不含空格) uri, flag = line.split(maxsplit=1) proto_map[uri] = flag # 读取主机地址文件,构建URI->主机的映射 with open(host_file, 'r') as f: for line in f: line = line.strip() if not line: continue uri, host = line.split(maxsplit=1) host_map[uri] = host # 读取后端URI文件,构建URI->后端的映射 with open(backend_file, 'r') as f: for line in f: line = line.strip() if not line: continue uri, backend = line.split(maxsplit=1) backend_map[uri] = backend # 处理前端URI并生成最终输出 with open(frontend_file, 'r') as f_in, open(output_file, 'w') as f_out: for line in f_in: frontend_uri = line.strip() if not frontend_uri: continue # 从字典取对应值,没有则用N/A填充 proto = proto_map.get(frontend_uri, "N/A") host = host_map.get(frontend_uri, "N/A") backend = backend_map.get(frontend_uri, "N/A") # 拼接成指定格式 output_line = f"{frontend_uri} | {proto} | {host} | {backend}" f_out.write(output_line + "\n") print(f"处理完成!结果已保存到 {output_file}")
关键细节说明
- 如果你的URI包含空格,把
split(maxsplit=1)换成适合的分割逻辑即可; - 代码用
strip()处理了每行首尾的空白,避免换行符、多余空格导致匹配失败; - 缺失字段用
N/A标记,你可以改成空字符串或其他自定义标记,按需调整。
命令行替代方案(awk)
要是你熟悉Linux命令行,用awk能更快处理,适合服务器环境:
# 先把三个关联文件合并成临时映射文件 awk '{print $1, $2}' proto_flags.txt > temp_map.txt awk '{print $1, $2}' hosts.txt >> temp_map.txt awk '{print $1, $2}' backend_uris.txt >> temp_map.txt # 遍历前端URI文件,匹配并生成结果 awk ' BEGIN {OFS=" | "} NR==FNR { if (!($1 in map)) map[$1] = "" map[$1] = map[$1] " " $2 next } { split(map[$1], arr) proto = arr[1] ? arr[1] : "N/A" host = arr[2] ? arr[2] : "N/A" backend = arr[3] ? arr[3] : "N/A" print $1, proto, host, backend } ' temp_map.txt frontend_uris.txt > final_result.txt # 清理临时文件 rm temp_map.txt
内容的提问来源于stack exchange,提问作者Philip
相关产品推荐
相关产品推荐

