创建句子组合 python
Create combination of sentences python
我正在尝试从词典中创建句子组合。让我解释。想象一下,我有这句话:"The weather is cool"
我有字典:dico = {'weather': ['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
但我不知道如何获得其他句子。
预先感谢您的帮助
你可以用 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']
我正在尝试从词典中创建句子组合。让我解释。想象一下,我有这句话:"The weather is cool" 我有字典:dico = {'weather': ['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
但我不知道如何获得其他句子。 预先感谢您的帮助
你可以用 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']