Python如何处理文本文件冒号后空格差异以生成正确字典
Python文本转字典空格分类错误解决方案
核心原因是提取分类key时没有清理首尾空白字符,对分割后的字符串调用strip()方法移除多余空白即可解决,两种常用实现场景如下:
场景1:直接从文本文件生成正确字典
逐行读取文件时同步清理空白:
result = {} # 替换为你的实际文件路径 with open('demo.txt', 'r', encoding='utf-8') as f: for line in f: # 先清理行首尾的换行、空格,跳过空行 line = line.strip() if not line: continue # 按冒号最多分割1次,避免实体/分类里含冒号时拆分出错 entity, category = line.split(':', 1) # 分别清理实体和分类的首尾空白 entity = entity.strip() category = category.strip() # 写入结果字典 if category not in result: result[category] = [] result[category].append(entity)
执行后得到的result输出为:
{'animal': ['pig', 'dog', 'cat'], 'thing': ['car']}
场景2:已有错误字典的修复
如果已经生成了带多余空格key的旧字典,可直接遍历清理合并:
old_dict = {" animal": ['pig','dog'], "animal" : ["cat"], " thing" : ['car']} new_dict = {} for raw_key, value_list in old_dict.items(): # 清理key的首尾空白 clean_key = raw_key.strip() if clean_key not in new_dict: new_dict[clean_key] = [] # 合并同分类的实体列表 new_dict[clean_key].extend(value_list)
处理后得到的new_dict和直接生成的正确字典效果一致。
内容的提问来源于stack exchange,提问作者mj_1234
相关产品推荐
相关产品推荐

