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

如何从testText.txt文本文件创建复杂字典?

从testText.txt生成复杂字典的解决方案

我来帮你搞定这个问题!从你提供的文本文件结构来看,它用#Rooms、#Doors、#Items作为模块分隔符,每个模块下是对应的条目。我们可以用Python编写一个解析函数,把这些内容转换成结构化的复杂字典,方便后续使用。

步骤1:分析文本结构

先明确每个模块的格式:

  • Rooms:每行是room [房间名称],比如room Hall
  • Doors:每行是door [方向] [状态] [房间1] [房间2],比如door N open Hall Bedroom
  • Items:每行是item [物品名称] [位置/属性],比如item car G

步骤2:编写解析函数

下面是完整的Python代码,它会把文本内容解析成包含房间、门、物品,以及房间详情的复杂字典:

def parse_text_to_dict(file_path):
    # 读取文件内容
    with open(file_path, 'r') as f:
        content = f.read()
    
    # 分割成各个模块(过滤空内容)
    sections = [s.strip() for s in content.split('#') if s.strip()]
    result = {}
    
    for section in sections:
        lines = section.split('\n')
        # 获取模块名称(Rooms/Doors/Items)
        section_key = lines[0].split()[0]
        # 获取模块下的所有条目(过滤空行)
        entries = [line.strip() for line in lines[1:] if line.strip()]
        
        if section_key == 'Rooms':
            # 提取所有房间名称
            rooms = [entry.split()[1] for entry in entries]
            result['rooms'] = rooms
            # 初始化每个房间的详情字典(关联门和物品)
            result['room_details'] = {room: {'doors': [], 'items': []} for room in rooms}
        
        elif section_key == 'Doors':
            result['doors'] = []
            for entry in entries:
                parts = entry.split()
                # 解析门的信息:方向、状态、连接的两个房间
                door_info = {
                    'direction': parts[1],
                    'status': parts[2],
                    'connects': [parts[3], parts[4]]
                }
                result['doors'].append(door_info)
                # 把门信息关联到对应的两个房间
                result['room_details'][parts[3]]['doors'].append(door_info)
                result['room_details'][parts[4]]['doors'].append(door_info)
        
        elif section_key == 'Items':
            result['items'] = []
            for entry in entries:
                parts = entry.split()
                # 解析物品信息:名称、位置(如果有其他属性可以扩展)
                item_info = {
                    'name': parts[1],
                    'location': parts[2] if len(parts) >= 3 else 'unknown'
                }
                result['items'].append(item_info)
                # 把物品关联到对应房间的详情中
                if item_info['location'] in result['room_details']:
                    result['room_details'][item_info['location']]['items'].append(item_info['name'])
    
    return result

# 使用函数生成字典
game_data = parse_text_to_dict('testText.txt')

# 用pprint美化输出结果(需要先导入pprint)
import pprint
pprint.pprint(game_data)

步骤3:解析结果说明

运行上面的代码后,你会得到一个结构清晰的字典,包含以下几个核心部分:

  • game_data['rooms']:所有房间名称的列表
  • game_data['doors']:所有门的详细信息列表,每个门是一个包含方向、状态、连接房间的字典
  • game_data['items']:所有物品的详细信息列表,每个物品包含名称和位置
  • game_data['room_details']:按房间名称分组的详情,每个房间下有对应的门列表和物品列表,方便快速查询某个房间的所有关联信息

自定义调整提示

如果你的文本文件格式有细微变化(比如Items部分有更多属性),只需要调整对应模块的解析逻辑即可。比如如果物品行是item car Garage red,可以修改item_info为:

item_info = {
    'name': parts[1],
    'location': parts[2],
    'color': parts[3]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 08:24:25