python 大括号嵌套,python随机化器通过双嵌套在大括号之间获取随机文本

Python正则表达式不支持嵌套结构,因此您必须找到其他解析字符串的方法。

下面是我的快速学习:def randomize(text):

start= text.find('{')

if start==-1: #if there are no curly braces, there's nothing to randomize

return text

# parse the choices we have

end= start

word_start= start+1

nesting_level= 0

choices= [] # list of |-separated values

while True:

end+= 1

try:

char= text[end]

except IndexError:

break # if there's no matching closing brace, we'll pretend there is.

if char=='{':

nesting_level+= 1

elif char=='}':

if nesting_level==0: # matching closing brace found - stop parsing.

break

nesting_level-= 1

elif char=='|' and nesting_level==0:

# put all text up to this pipe into the list

choices.append(text[word_start:end])

word_start= end+1

# there's no pipe character after the last choice, so we have to add it to the list now

choices.append(text[word_start:end])

# recursively call this function on each choice

choices= [randomize(t) for t in choices]

# return the text up to the opening brace, a randomly chosen string, and

# don't forget to randomize the text after the closing brace

return text[:start] + random.choice(choices) + randomize(text[end+1:])

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值