首页 > 解决方案 > 在Python中的字符串列表中提取特定字符串

问题描述

我有一个字符串列表:

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."]

我想将信息提取到 2 个单独的列表中,每个列表都包含 A 和 B 的内容。

例如:

List_A = ['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']

List_B = ['B: Really? What is that?', 'B: It's not bad', 'I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']

有没有办法在 Python 中执行任务?我真的很感激帮助!

标签: pythonstringnlp

解决方案


尝试使用列表推导:

List = sum([i.split('|') for i in List], [])
List_A = [i for i in List if i[0] == "A"]
List_B = [i for i in List if i[0] == "B"]

现在:

print(List_A)

将会:

['A: I want to do something cool!', 'A: Lets me show you.', 'A: How do you think about it?!', 'A: Thank you. What do you up to?']

和:

print(List_B)

将会:

['B: Really? What is that?', "B: It's not bad", 'B: I have no idea. Lets hangaround', 'B: or maybe we can go for a drink.']

推荐阅读