如何用两层字典实现戏剧文本指定幕、场景、角色台词搜索功能
Python戏剧文本台词搜索功能实现修改方案
首先约定play.txt的常规戏剧格式(可根据你实际的文件格式调整解析规则):
ACT I SCENE I HAMLET To be, or not to be: that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, HORATIO My lord, I came to see your father's funeral.
完整修改后代码
# 初始化第一层字典:key为幕名称,value为第二层字典 play_dict = {} # 临时变量存储解析进度 current_act = None current_scene = None current_char = None current_lines = [] with open('play.txt', 'r', encoding='utf-8') as inFile: for line in inFile: stripped_line = line.strip() # 跳过空行,空行判定为当前角色台词结束的标记 if not stripped_line: if current_act and current_scene and current_char and current_lines: # 第一层字典没有当前幕时,先初始化第二层字典 if current_act not in play_dict: play_dict[current_act] = {} # 第二层字典key用(场景,角色)元组,符合两层字典的要求 scene_char_key = (current_scene, current_char) if scene_char_key not in play_dict[current_act]: play_dict[current_act][scene_char_key] = "" # 拼接台词存入字典 play_dict[current_act][scene_char_key] += '\n'.join(current_lines) + '\n' # 重置临时缓存 current_lines = [] current_char = None continue # 识别幕 if stripped_line.startswith('ACT'): current_act = stripped_line current_scene = None continue # 识别场景 if stripped_line.startswith('SCENE'): current_scene = stripped_line continue # 识别角色:默认角色名为全大写,无标点,可根据实际格式调整 if stripped_line.isupper() and not any(c in stripped_line for c in ('.', ',', '?', '!')): current_char = stripped_line continue # 剩余内容为当前角色台词,存入临时缓存 if current_char: current_lines.append(stripped_line) # 接收用户输入 target_act = input('Which act do you want to learn about?').strip() target_scene = input('Which scene do you want to see within this act?').strip() target_char = input('Which character do you want to see the lines of?').strip() # 查询输出 query_key = (target_scene, target_char) if target_act in play_dict: if query_key in play_dict[target_act]: print(f"\n{target_char} 在 {target_act} {target_scene} 的台词:\n") print(play_dict[target_act][query_key]) else: print(f"未找到对应内容,请检查输入的场景、角色是否正确") else: print(f"未找到对应幕,请检查输入的幕名称是否正确")
核心修改说明
- 命名规范:避免使用
Dict这种和Python内置类型重名的变量,改为语义清晰的play_dict - 解析逻辑补全:新增临时变量记录当前解析到的幕、场景、角色和临时台词缓存,处理空行作为台词结束的分隔标记
- 字典结构符合要求:第一层key为幕名称,第二层字典用
(场景, 角色)元组作为key直接映射台词,完全满足两层字典的实现要求 - 错误修复:修正了原代码中
starts with拼写错误、b变量未定义等问题 - 容错处理:新增输入不存在时的提示,避免代码直接报错
- 拓展提示:如果允许使用三层字典,可将第二层key设为场景,第二层value为「角色-台词」映射的第三层字典,查询逻辑会更直观,修改成本很低
内容的提问来源于stack exchange,提问作者Greg
相关产品推荐
相关产品推荐

