Extract specific string in a list of string in Python

Viewed 572

I have a list of strings:

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

I want to extract the information into 2 separate lists, each containing the content of A & B.

For example:

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

Is there any way to perform the task in Python? I really appreciate the help!

3 Answers

Try using list comprehensions:

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

And now:

print(List_A)

Would be:

['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?']

And:

print(List_B)

Would be:

['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.']

You can split each string on |, iterate over each sentence and add them to a dictionary based on the first letter of each sentence.

from collections import defaultdict

d = defaultdict(list)
for line in data:
    split = line.split("|")
    for sentence in split:
        key = sentence[0]
        d[key].append(sentence)

print(d["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(d["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.']

An easy solution -

list1 = []
list2 = []
for j in List:
    for i in j.split('|'):
        if i.startswith('A'):
            list1.append(i)

        if i.startswith('B'):
            list2.append(i)


print(list1)
print()
print(list2)

Result:

['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?']

['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.']

You could use list comprehension instead. But it was answered by other user

Related