Ad

Generate Text From A Given Template

- 1 answer

For example I have a string such as

    text = '{Hello|Good morning|Hi}{. We|, we} have a {good |best }offer for you.'

How can I generate a set of all possible strings with variants of words in braces?

Hello. We have a good offer for you.

Good morning, we have a best offer for you.

etc...

Ad

Answer

You can use the re and random module, like this:

import random
import re

def randomize(match):
    res = match.group(1).split('|')
    random.shuffle(res)
    return res[0]

def random_sentence(tpl):
    return re.sub(r'{(.*?)}', randomize, tpl)

tpl = '{Hello|Good morning|Hi}{. We|, we} have a {good |best }offer for you.'
print(random_sentence(tpl))
Ad
source: stackoverflow.com
Ad