Python 3.7读取文档并将指定行存入字典/数组的问题
提取计算机规格到目标字典结构
你需要读取自动化生成的文件,将每个计算机对应的spec 1/spec 2/spec 3存入指定结构的字典,以下是可行的实现方案:
输入文件格式
Computer #1 - gaming spec 1 = something spec 2 = something spec 3 = something other stuff = sadas computer #2 - coding spec 1 = something spec 2 = something spec 3 = something other stuff = sadas computer #n - etc spec 1 = something spec 2 = something spec 3 = something other stuff = sadas
目标字典结构
data = { "computer #1": [spec1, spec2, spec3], "computer #2": [spec1, spec2, spec3], "computer #n": [spec1, spec2, spec3] }
修正后的Python代码
# 初始化空字典 data = {} # 跟踪当前处理的计算机条目 current_computer = None with open("your_file_path.txt", "r") as file_read: lines = file_read.readlines() for line in lines: # 去除首尾空白字符,规避缩进、换行符的干扰 stripped_line = line.strip() # 跳过空行 if not stripped_line: continue # 识别计算机条目行 if "computer #" in stripped_line.lower(): # 提取计算机编号作为字典键,统一转小写避免大小写差异 computer_key = stripped_line.split("-")[0].strip().lower() data[computer_key] = [] current_computer = computer_key # 识别spec行并关联到当前计算机 elif stripped_line.startswith("spec") and current_computer is not None: # 方案1:直接保留处理后的spec行内容 data[current_computer].append(stripped_line) # 方案2:提取等号后的具体值(取消注释即可使用) # spec_value = stripped_line.split("=")[1].strip() # data[current_computer].append(spec_value)
关键逻辑说明
- 用
current_computer变量跟踪当前处理的计算机条目,确保spec行能精准对应到字典的对应键 - 先去除每行首尾空白,避免缩进、换行符干扰判断逻辑
- 提取计算机键时统一转小写,兼容原文件中
Computer和computer的大小写差异 - 可根据需求选择保留完整spec行,或仅提取等号后的具体值
内容的提问来源于stack exchange,提问作者Ahmed Arafat
相关产品推荐
相关产品推荐

