创建句子python的组合

时间:2018-08-31 08:39:08

标签: python dictionary replace sentence

我正在尝试根据词典创建句子的组合。让我解释。想象一下我有这样一句话:“天气很酷” 而且我有字典:dico = {'天气':['sun','rain'],'cool':['fabulous','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

但是我不知道该如何让其他句子。 预先感谢您的帮助

1 个答案:

答案 0 :(得分:2)

您可以为此使用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']