splitting a sentences in to list of sentences by specific combinations

Viewed 35

I have a sentence

string = 'senior engineer/developer in school/university'

my except output combinations are

string_list = ['senior engineer in school', 'senior engineer in university',
               'senior developer in school', 'senior developer in school]

I want to make a combination by splitting the sentence based on "/". Is there any option to split in such way? I was looking at itertools but its not the way i am expecting

x = string.split('/')
x = [y.split() for y in x]
print(list(combinations(x,len(x))))
1 Answers

Use itertools.product and clever splitting:

from itertools import product

list(map(' '.join, product(*(s.split('/') for s in string.split()))))
# ['senior engineer in school', 
#  'senior engineer in university', 
#  'senior developer in school', 
#  'senior developer in university']

This splits by space first and each token by slash second. product then builds all combinations from the resulting nested iterable. As those combinations are produced as tuples, we ' '.join them back into sentences (str).

Related