如何使用具有多个嵌套的模式生成文本?

时间:2016-11-10 15:28:00

标签: python regex

我得到了如下模式:

  

{在我的{beautiful | wonderful}世界中我是{最好的一个|宽松} |不是今天,{man | guy}}

想得到随机结果:

  

在我精彩的世界里,我更宽松

     

在我美丽的世界里,我是最好的世界

     

不是今天,家伙

     

在我精彩的世界中,我是最好的世界

     

...

等等。我已经为一级嵌套模式编写了代码:

import random
import re

def replace_random(review):
    random_tags = re.findall(r"\{(.*?)\}", review, re.DOTALL)
    for random_tag in random_tags:
        choice = random.choice(random_tag.split('|'))
        review = review.replace('{'+random_tag+'}', choice)
    return review

print(replace_random('In my {beautiful|wonderful} world i\'m {the best one|looser}'))

但是如果我有多个嵌套(如上所述),它就不起作用了。如何递归?

1 个答案:

答案 0 :(得分:2)

替换不包含任何花括号的内部标记,然后如果还有任何标记,请重复此过程:

import random
import re

def replace_random(review):
    random_tags = re.findall(r"\{([^{}]*?)\}", review, re.DOTALL)
    for 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 my {beautiful|wonderful} world i'm {the best one|looser}|Not today, {man|guy}}"))

与当前代码一样,如果要在输出中使用文字大括号,则会出现问题。它也不是最有效的方式,因为它通常会被丢弃。但它可能会很好。