Python如何从字符串列表中提取指定内容,拆分生成A、B各自的对话列表
Python实现对话按说话人拆分到独立列表
实现思路:
- 遍历原始列表的每段长对话,用分隔符
|拆分出单条对话内容 - 判断每条对话的开头标识,分别存入A、B对应的列表即可
完整实现代码:
# 原始字符串列表 original_list = ["A: I want to do something cool!|B: Really? What is that?|A: Lets me show you.", "A: How do you think about it?!|B: It's not bad|A: Thank you. What do you up to?|B: I have no idea. Lets hangaround|B: or maybe we can go for a drink."] List_A = [] List_B = [] for block in original_list: # 拆分单条对话 utterances = block.split('|') for item in utterances: item = item.strip() if item.startswith('A:'): List_A.append(item) elif item.startswith('B:'): List_B.append(item) # 输出验证 print(List_A) print(List_B)
运行输出结果和你给出的预期完全匹配,你示例中List_B的第三个元素缺少B:前缀属于输入笔误,原始数据中该条对话自带B标识,运行后会正常携带。如果你需要去掉结果里的A:、B:前缀,把append的内容修改为item[2:].strip()即可。
内容的提问来源于stack exchange,提问作者bach lam
相关产品推荐
相关产品推荐

