用python创建句子组合

用python创建句子组合,python,dictionary,replace,sentence,Python,Dictionary,Replace,Sentence,我正在尝试从字典中创建一个句子组合。让我解释一下。想象一下,我有这样一句话:“天气很凉爽” 我的字典是:dico={'weather':['sun','rain'],'cool':['fabric','great']}。 我希望将以下内容作为输出: - The weather is fabulous - The weather is great - The sun is cool - The sun is fabulous - The sun is great - The rain is coo

我正在尝试从字典中创建一个句子组合。让我解释一下。想象一下,我有这样一句话:“天气很凉爽” 我的字典是:dico={'weather':['sun','rain'],'cool':['fabric','great']}。 我希望将以下内容作为输出:

- 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
以下是我目前的代码:

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]))
我得到:

The sun is cool
The rain is cool
The weather is fabulous
The weather is great
但我不知道如何理解其他句子。
提前感谢您的帮助

您可以为此使用
itertools.product

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

首先计算出您的算法,然后编码。编码样式:
用于范围内的n(len(j)):j[n]
可以替换为
用于范围内的n:n
谢谢您的回答!:)