创造句子组合

2024-04-26 23:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着从字典里创造一个句子的组合。让我解释一下。想象一下我有这样一句话:“天气很凉爽” 我的字典是:dico={weather':['sun','rain'],'cool':['fabulary','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

但我不知道怎么把其他的句子写出来。 事先谢谢你的帮助


Tags: theinfor字典issentencedico句子
1条回答
网友
1楼 · 发布于 2024-04-26 23:31:47

你可以用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']

相关问题 更多 >