I am trying to create a combination of sentences from dictionaries. Let me explain. Imagine that I have this sentence: "The weather is cool" And that I have as dictionary: dico = {'weather': ['sun', 'rain'],'cool': ['fabulous', 'great']}. I would like to have as output:
- The weather is fabulous
- The weather is great
- The sun is cool
- The sun is fabulous
- The sun is great
- The rain is cool
- The rain is fabulous
- The rain is great
Here is my code for the moment:
dico = {'weather': ['sun', 'rain'],'cool': ['fabulous', 'great']}
sentence = 'The weather is cool'
for i, j in dico.items():
for n in range(len(j)):
print(sentence.replace(i,j[n]))
And I get:
The sun is cool
The rain is cool
The weather is fabulous
The weather is great
But I don't know how to get the others sentences. Thank you in advance for your help
You can use itertools.product
for this
>>> from itertools import product
>>> sentence = "The weather is cool"
>>> dico = {'weather': ['sun', 'rain'],'cool': ['fabulous', 'great']}
>>>
>>> lst = [[word] + list(dico[word]) if word in dico else [word] for word in sentence.split()]
>>> lst
[['The'], ['weather', 'sun', 'rain'], ['is'], ['cool', 'fabulous', 'great']]
>>>
>>> res = [' '.join(line) for line in product(*lst)]
>>>
>>> pprint(res)
['The weather is cool',
'The weather is fabulous',
'The weather is great',
'The sun is cool',
'The sun is fabulous',
'The sun is great',
'The rain is cool',
'The rain is fabulous',
'The rain is great']