嘿,我需要创建简单的python随机数发生器。例如输入:python随机数发生器 - 在双层嵌套级别的大括号中获得随机文本
{{hey|hello|hi}|{privet|zdravstvuy|kak dela}|{bonjour|salut}}, can {you|u} give me advice?
和输出应该是:
hello, can you give me advice
我有一个脚本,它可以做到这一点,但只有一层嵌套
with open('text.txt', 'r') as text:
matches = re.findall('([^{}]+)', text.read())
words = []
for match in matches:
parts = match.split('|')
if parts[0]:
words.append(parts[random.randint(0, len(parts)-1)])
message = ''.join(words)
这是不够的,我)
对我而言,似乎你的输入遵循的语法对于简单的正则表达式有点复杂。我会说,构建一个适当的词法分析器,由分析器调用以产生输出。如果你不熟悉这个概念,我建议你先阅读理论:) – 2015-01-21 11:28:34
你正在寻找递归正则表达式匹配。见:http://stackoverflow.com/questions/1656859/how-can-a-recursive-regexp-be-implemented-in-python – 2015-01-21 11:29:30
@ KarelKubat哦,不,我不需要这个。我只想从大括号中得到随机文本,其中包含另一个大括号 – 2015-01-21 11:29:57