python - How can i generate text using patterns with multiple nesting? -
i got pattern such as:
{in {beautiful|wonderful} world i'm {the best one|looser}|not today, {man|guy}}
and want random results:
in wonderful world i'm looser
in beautiful world i'm best one
not today, guy
in wonderful world i'm best one
...
and on. i've got working code one-level nesting pattern:
import random import re def replace_random(review): random_tags = re.findall(r"\{(.*?)\}", review, re.dotall) random_tag in random_tags: choice = random.choice(random_tag.split('|')) review = review.replace('{'+random_tag+'}', choice) return review print(replace_random('in {beautiful|wonderful} world i\'m {the best one|looser}'))
but if have multiple nesting(as above), doesn't work. how make recursively?
replace inner tags don't contain curly brackets, , if there's tags left, repeat process:
import random import re def replace_random(review): random_tags = re.findall(r"\{([^{}]*?)\}", review, re.dotall) random_tag in random_tags: choice = random.choice(random_tag.split('|')) review = review.replace('{' + random_tag + '}', choice) if '{' in review or '}' in review: return replace_random(review) return review print(replace_random("{in {beautiful|wonderful} world i'm {the best one|looser}|not today, {man|guy}}"))
like current code, have problems if want have literal curly brackets in output. it's not efficient way work thrown away. fine.
Comments
Post a Comment