Создать комбинацию предложений Python - PullRequest
0 голосов
/ 31 августа 2018

Я пытаюсь создать комбинацию предложений из словарей. Позволь мне объяснить. Представьте себе, что у меня есть это предложение: "Погода прохладная" И что у меня есть как словарь: 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

Но я не знаю, как получить другие предложения. Заранее благодарю за помощь

1 Ответ

0 голосов
/ 31 августа 2018

Вы можете использовать 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']
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...