我正在寻找一种算法或一些建议来实现它。
输入:
"{1|2} word {3|4}"
输出:
["1 word 3", "1 word 4", "2 word 3", "2 word 4"]
另外,我想支持嵌套结构——"{1|2{0|1}}" -> ["1", "20", "21"]
我意识到这个问题太笼统了,但不想实现轮子。也许你看到了类似的事情。
UPD
from pyparsing import *
from collections import deque
s = u"{1|2} {3|4}"
deque = deque()
def mesh_lists(listOne, listTwo):
result = []
for l1 in listOne:
for l2 in listTwo:
firstWord = str(l1).strip()
secondWord = str(l2).strip()
result.append(" " + firstWord + " " + l2 + " ")
return result
def action(string, pos, token):
global deque
deque.append(list(token[0]))
def processDeque():
global deque
while len(deque) > 1:
l1 = deque.popleft()
l2 = deque.popleft()
res = mesh_lists(l1,l2)
deque.appendleft(res)
return [x.strip() for x in deque[0]]
_lcurl = Suppress('{')
_rcurl = Suppress('}')
_pipe = Suppress('|')
word = Regex("[^{|}]+")
varBlock = Forward()
entry = word | varBlock
varList = Group(entry + ZeroOrMore(_pipe + entry))
varBlock << (_lcurl + Optional(varList) + _rcurl).setParseAction(action)
template = ZeroOrMore(entry)
res = template.parseString(s)
print processDeque()
它仅支持“{||}{||}”结构。没有空话,没有嵌套结构。