简体   繁体   中英

Create combination of sentences python

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM