基于字典ref属性拼接完整连贯语句的技术实现问题
问题
给定字典列表clause_list,其中子句字典通过ref属性关联父句,需要拼接出完整连贯的语句(如预期输出"hi I'm Simone"),避免生成"hi I'm"或"I'm Simone"这类不完整语句。当前尝试的代码仍会输出非预期内容,求解决办法。
代码示例
clause_list = [ {"id": "T1", "text": "hi"}, {"id": "T2", "text": "I'm", "ref": "T1"}, {"id": "T3", "text": "Simone", "ref": "T2"}, ]
当前尝试的代码
for c in clause_list: for child in clause_list: try: if c["id"] == child["ref"] and "ref" not in c.keys(): print(c["text"], child["text"]) elif c["id"] == child["ref"] and "ref" in c.keys(): for father in clause_list: if father["id"] == c["ref"] and "ref" not in father.keys(): print(father["text"], c["text"], child["text"]) except KeyError: pass
解决方案
当前代码仅能处理最多三层的关联逻辑,且无法适配任意长度的关联链条,导致输出不完整语句。可以通过构建映射+遍历关联链的方式解决:
完整代码实现
clause_list = [ {"id": "T1", "text": "hi"}, {"id": "T2", "text": "I'm", "ref": "T1"}, {"id": "T3", "text": "Simone", "ref": "T2"}, ] # 构建id到子句的映射,快速查找子句 id_to_clause = {clause["id"]: clause for clause in clause_list} # 构建父id到子节点的映射,方便遍历关联关系 parent_to_children = {} for clause in clause_list: if "ref" in clause: parent_id = clause["ref"] parent_to_children.setdefault(parent_id, []).append(clause) # 定位所有根节点(没有ref属性的子句) root_clauses = [clause for clause in clause_list if "ref" not in clause] # 拼接完整语句 for root in root_clauses: current_clause = root full_sentence = [current_clause["text"]] # 顺着关联链条遍历到末端 while current_clause["id"] in parent_to_children: # 假设每个父节点仅一个子节点,多子节点场景可按需调整逻辑 current_clause = parent_to_children[current_clause["id"]][0] full_sentence.append(current_clause["text"]) print(" ".join(full_sentence))
代码说明
- 映射结构避免了多层嵌套循环,提升查找效率和代码可读性
- 通过循环遍历关联链条,确保从根节点到末端节点的所有文本都被拼接,不会出现不完整语句
- 若存在多根节点或一个父节点对应多个子节点的场景,可根据实际需求调整遍历逻辑
内容的提问来源于stack exchange,提问作者93simon
相关产品推荐
相关产品推荐

